I want read text file and store in array then show.
This is my code:
int i = 0, line = 5;
char ch[100];
FILE *myfile;
myfile = fopen("test.txt","r");
if (myfile== NULL)
{
printf("can not open file \n");
return 1;
}
while(line--){
fscanf(myfile,"%s",&ch[i]);
i++;
printf("\n%s", &ch[i]);
}
fclose(myfile);
return 0;
}
This is my text:
test 123562
856
59986
But result:
est
2356
56
9986
What is wrong? :(
ch[i]
is holding a single character.
Statement
fscanf(myfile,"%s",&ch[i]);
will scan string to
ch[i]
which can hold only one character.
There is no place for
'\\0'
which leads your program to
undefined behavior .
Change
fscanf(myfile,"%s",&ch[i]);
to
fscanf(myfile,"%s",ch);
Previous answer was wrong. Behavior of program is well defined but you are scanning the file in a wrong manner. Your program will work as expected if you place i++;
after printf
statement.
while(line--){ fscanf(myfile,"%s",&ch[i]); printf("\\n%s", &ch[i]); i++; }
The reason is that &ch[i]
is a pointer to the i th element of the array and string will be stored in array starting at position i
. For the input given, this will work because the given array is large enough to hold the string.
You can do this as:
while(line--){ fscanf(myfile,"%s",ch); printf("\\n%s", ch); i++; }
but it will overwrite the array ch
each time a string is scanned to it. Better to use a two dimensional array to store strings and read file with fgets
.
You're not going to be able to fit five lines in the single char ch[100]
array; that's just an array of 100 characters.
You can make it an array of arrays, ie char ln[5][100]
which will give you room for five lines of 100 characters each.
Then you of course need to index into that array in the loop, ie:
for(int i = 0; i < 5; ++i)
{
if(fgets(ln[i], sizeof ln[i], myfile) == NULL)
{
fprintf(stderr, "Read error on line %d\n", i);
exit(1);
}
}
This uses fgets()
which is much better suited at reading in whole lines; fscanf()
will stop at whitespace with %s
which is seldom what you want.
There is no need to use the ampersand in the scanf while getting the string. Make that into like this.
fscanf(myfile,"%s",&ch[i]);
to
fscanf(myfile,"%s",ch);
&ch[i]
It will get the character for i th position in that array. If you want to get like that you can use the %c
instead of %s
. And change this one to.
printf("\n%s", ch);
While printing the string when you use the ampersand(&) that will access the address of that variable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.