hey so i m trying to read numbers from text file and put them into an array but ive been getting weird numbers when i try to print them. text file looks like:
45
77
8
...
i guess theres something wrong with the loop i m using but i cant seem to find out what.
thanks for your help!
code:
#define MAX_ARRAY_SIZE 20
int main(int argc, char * argv[])
{
FILE *myFile;
int myArray[MAX_ARRAY_SIZE];
//char filename[32];
//printf("enter filename\n");
//scanf("%s", filename);
myFile = fopen("asdf.txt", "r");
if (!myFile) {
printf("cant open file\n");
return 1;
}
int status;
int i = 0;
while ((status = fscanf(myFile, "%2d", &myArray[i])) == 1 && i < MAX_ARRAY_SIZE - 1) {
++i;
}
fclose(myFile);
int a;
for (a = 0; i < MAX_ARRAY_SIZE; ++i) {
printf("%d ", myArray[i]);
}
printf("\n");
return 0;
}
The problem is in your print loop:
for (a = 0; i < MAX_ARRAY_SIZE; ++i)
There is no guarantee you are reading MAX_ARRAY_SIZE values. Also, if you ar using 'a' as your loop iterator, then you need to use 'a'. Your loop should be:
for (a = 0; a < i; ++a)
printf("%d ", myArray[a]);
You also do not need a field-width in your format-specifier, fscanf(myFile, " %d", &myArray[i])) will do.
Try this
while ((status = fscanf(myFile, "%d\n", &myArray[i])) == 1 && i < MAX_ARRAY_SIZE - 1) {
++i;
}
True... I have not seen print loop code.. Sorry.
Problem is in print loop not fscan, please ignore my answer
Related
I am new to C programming and I am getting a THREAD 1: EXC_BAD_ACCESS(code = 1, address 0x68)
when I run my program. The purpose of my code is to read from a txt file that contains positive and negative numbers and do something with it.
#include <stdio.h>
int main (int argc, const char * argv[]) {
FILE *file = fopen("data.txt", "r");
int array[100];
int i = 0;
int num;
while( fscanf(file, "%d" , &num) == 1) { // I RECEIVE THE ERROR HERE
array[i] = num;
printf("%d", array[i]);
i++;
}
fclose(file);
for(int j = 0; j < sizeof(array); j++){
printf("%d", array[j]);
}
}
After
FILE *file = fopen("data.txt", "r");
Say
if(file == 0) {
perror("fopen");
exit(1);
}
Just a guess, the rest of the code looks ok, so likely this is the problem.
Also worth noting that you might have more than 100 numbers in your file, in which case you will blow past the size of your array. Try replacing the while loop with this code:
for (int i = 0; i < 100 && ( fscanf(file, "%d" , &num) == 1); ++i)
{
array[i] = num;
printf("%d", array[i]);
}
Do you have the file "data.txt" created and local?
touch data.txt
echo 111 222 333 444 555 > data.txt
Check that your file open succeeded.
Here is a working version,
#include <stdio.h>
#include <stdlib.h> //for exit
int main (int argc, const char * argv[])
{
FILE *fh; //reminder that you have a file handle, not a file name
if( ! (fh= fopen("data.txt", "r") ) )
{
printf("open %s failed\n", "data.txt"); exit(1);
}
int array[100];
int idx = 0; //never use 'i', too hard to find
int num;
while( fscanf(fh, "%d" , &num) == 1) { // I RECEIVE THE ERROR HERE
array[idx] = num;
printf("%d,", array[idx]);
idx++;
}
printf("\n");
fclose(fh);
//you only have idx numbers (0..idx-1)
int jdx;
for(jdx = 0; jdx<idx; jdx++)
{
printf("%d,", array[jdx]);
}
printf("\n");
}
image of issue with output
I'm reading a set of numbers from a file (1 2 3 4 5 6 7) and when I print them out in the while loop it returns the correct numbers. In the for loop directly below it, it's returning random numbers (under loop through array). Anyone know what is going on?
#include <stdio.h>
int main(int argc, char* argv[])
{
if(argc != 2){
printf("%s\n", "Wrong number of arguments");
}
else{
char* filename = argv[1];
printf("%s\n", filename);
FILE* fp = fopen(filename, "r");
int arrSize;
int array[arrSize];
int i = 0;
fscanf(fp, "%d\n", &arrSize);
printf("%d\n", arrSize);
while (fscanf(fp, "%d", &array[i]) == 1) {
printf("%d\n", array[i]);
i = i+1;
}
printf("%s\n", "Loop through array");
for (int j = 0; j < arrSize; j++) {
printf("%d", array[j]);
printf("\n");
}
fclose(fp);
}
}
You have:
int arrSize;
int array[arrSize];
int i = 0;
fscanf(fp, "%d\n", &arrSize);
When you define array, you have no idea what value is in arrSize; it is uninitialized.
You need:
int arrSize;
int i = 0;
fscanf(fp, "%d\n", &arrSize);
if (arrSize <= 0 || arrSize > MAX_ARRAY_SIZE)
…deal with error condition…
int array[arrSize];
You might want to think about writing the first loop as:
for (int i = 0; i < arrSize && fscanf(fp, "%d", &array[i]) == 1; i++)
printf("%d\n", array[i]);
This avoids overflowing the bounds of the array you have allocated. You then don't need the separate declaration of i either. The braces are optional; I wouldn't use them for a single, simple statement like the printf() call, but many people always use them. The braces become necessary, of course, if the loop is revised to:
for (int i = 0; i < arrSize; i++)
{
if (fscanf(fp, "%d", &array[i]) != 1)
break;
printf("%d\n", array[i]);
}
It's good that you test for fscanf(…) == 1; people often mistakenly test against EOF.
Look at this piece of code.
int arrSize;
int array[arrSize];
int i = 0;
fscanf(fp, "%d\n", &arrSize);
What do you think what will happen?
You are declaring an array without defining its size.
int arrSize;
fscanf(fp, "%d\n", &arrSize);
int array[arrSize];
I tried to read a file containing an empty box of '*', the error message doesn't get printed, so the file is opened, but the scan doesn't work. I tried to print the count variable, and the value of count is 0. I don't really know where the fault is. Please help... Thanks
the file content that I want to read
int openmap(int file_no){
char filename[32];
char mapp[100][100];
int number;
int count;
int x[100];
int nomor = 1;
for(int i = 1; i <= file_no; i++){
sprintf(filename, "map%d.txt", i);
FILE *test = fopen(filename,"r");
if(test)
{
printf("%2d. Map %d\n", nomor, i);
x[nomor-1] = i;
nomor++;
fclose(test);
}else if(!test && i > file_no){
printf("No map available!");
return 1;
}
}
do{
printf("[0 to cancel] [1 - %d]>> ", nomor-1);
scanf("%d", &number);
}while(number < 0 || number > file_no);
if(number > 0){
sprintf(filename,"map%d.txt", x[number-1]);
printf("%s", filename);
FILE *open = fopen(filename, "r");
if(!open){
printf("error");
}
while(!feof){
fscanf(open, "%[^\n]\n", mapp[count]);
count++;
}
fclose(open);
for(int i = 0; i < count ; i++){
printf("%s\n", mapp[i]);
}
}
}
I created a small test program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main () {
char mapp[100][100];
int i, count = 0;
char filename[32];
sprintf(filename, "test.txt");
FILE *open = fopen(filename, "r");
if(!open){
printf("error");
}
while(!feof(open)){
fscanf(open, "%[^\n]\n", mapp[count]);
count++;
}
fclose(open);
for(i = 0; i < count ; i++){
printf("%s\n", mapp[i]);
}
}
as far as i can see the only issue you have regarding the relevant section is your while loop condition, you should use: while(!feof(open)) - i tested my solution and it works so it seems that this is the only issue in your solution
I've created a project that reads numbers from a text file and draws an isometric projection of it, but now I'm trying to create a program that generates numbers from 0-9 and writes them in the document. This is what my code looks like, but the document remains empty. I'm under the assumption that the error is either in my rand() function usage, or when I convert the integers to characters.
Thank you in advance for all the input, and I apologize if it's just an operator error. I'm pretty new to this stuff:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char str[10];
FILE *fptr;
int i;
int num;
char num2;
i = 0;
fptr = fopen("map.fdf", "w");
if (fptr == NULL)
{
printf("ERROR Creating File!");
exit(1);
}
while (str[i] != '\0')
{
num = rand() % 10;
num2 = num + '0';
str[i] = num2;
i += 1;
}
puts(str);
fprintf(fptr,"%s", str);
fclose(fptr);
return (0);
}
I don't understand your while loop, it seems to wait for some condition that it doesn't contain code to make happen.
Anyway, how about not re-inventing how to convert single-digit integers to characters, and instead using higher-level I/O functions to just print to the file? That's why they're there, after all. :)
for (int i = 0; i < 10; ++i)
{
fprintf(fptr, "%d", rand() % 10);
}
fprintf(fptr, "\n"); /* Probably nice to make it a line. */
If you really must make do without for, you can of course always manually transform it into a while loop:
int i = 0;
while(i++ < 10)
{
fprintf(fptr, "%d", rand() % 10);
}
Your "str" is uninitialized, but apparently has a '\0' character as it's first element, so the while loop does not execute.
FILE *fn;
int num, n, range;
printf("Enter number of positive integer:");
scanf("%d", &n);
printf("Enter max integer:");
scanf("%d", &range);
fn=fopen("number.txt", "w");
for (int i=0; i<n; ++i) {
num = (rand()%range) + 1;
fprintf(fn, "%d\n", num);
}
fclose(fn);
I am new to C programming and I am getting a THREAD 1: EXC_BAD_ACCESS(code = 1, address 0x68)
when I run my program. The purpose of my code is to read from a txt file that contains positive and negative numbers and do something with it.
#include <stdio.h>
int main (int argc, const char * argv[]) {
FILE *file = fopen("data.txt", "r");
int array[100];
int i = 0;
int num;
while( fscanf(file, "%d" , &num) == 1) { // I RECEIVE THE ERROR HERE
array[i] = num;
printf("%d", array[i]);
i++;
}
fclose(file);
for(int j = 0; j < sizeof(array); j++){
printf("%d", array[j]);
}
}
After
FILE *file = fopen("data.txt", "r");
Say
if(file == 0) {
perror("fopen");
exit(1);
}
Just a guess, the rest of the code looks ok, so likely this is the problem.
Also worth noting that you might have more than 100 numbers in your file, in which case you will blow past the size of your array. Try replacing the while loop with this code:
for (int i = 0; i < 100 && ( fscanf(file, "%d" , &num) == 1); ++i)
{
array[i] = num;
printf("%d", array[i]);
}
Do you have the file "data.txt" created and local?
touch data.txt
echo 111 222 333 444 555 > data.txt
Check that your file open succeeded.
Here is a working version,
#include <stdio.h>
#include <stdlib.h> //for exit
int main (int argc, const char * argv[])
{
FILE *fh; //reminder that you have a file handle, not a file name
if( ! (fh= fopen("data.txt", "r") ) )
{
printf("open %s failed\n", "data.txt"); exit(1);
}
int array[100];
int idx = 0; //never use 'i', too hard to find
int num;
while( fscanf(fh, "%d" , &num) == 1) { // I RECEIVE THE ERROR HERE
array[idx] = num;
printf("%d,", array[idx]);
idx++;
}
printf("\n");
fclose(fh);
//you only have idx numbers (0..idx-1)
int jdx;
for(jdx = 0; jdx<idx; jdx++)
{
printf("%d,", array[jdx]);
}
printf("\n");
}