How to read from a sequential txt file
Hi,
I want to read in two char[] and a int from txt file then print them to the screen.
The problem is when output to the screen, the space is missing and get extra iput at the end of file.
The input file (e:\\text.txt) consists of
Hong Kong, China, 1\n
Tokyo, Japan, 2\n
Szhen, China, 3\n
Code:
#include <stdio.h>
int main()
{
FILE *fp=fopen("e:\\text.txt", "r");
char city[256]; /*city name: 256 long */
char country[256]; /*country name: 256 long*/
int pop; /*Country population*/
while(!feof(fp))
{
fscanf(fp, "%s%s%d", city,country, &pop);
printf("%s%s%d",city,country, pop);
}
fclose(fp);
getchar();
return 0;
}
---------------------------------
Output
HongKong,256China,1256Tokyo,Japan,2Szhen,China,3Szhen,China,3
--------------------------------
I have noted
1. number 256 add to it, does it mean a space?
2. why Szhen,China,3 input twice?
--------------------------------
Question
1. Does the output of sequential file output always look like
data1data2..........datan
If yes
2. How to print add a new line to the input int, ie. after input 1, 2, 3
3. How to get rid of extra input?
---------------------------------------------------
I have seen on some tutorial, they use %[^\n] to delimit the input, what does it mean?
------------------------------
Can anyone please help.
Thanks
Henry