So i want to read some strings from a text file that are seperated with spaces. The code i have been using is this:
int main() {
char name[9];
char surname[20];
char phone[10];
int code, nscan;
char termch;
FILE* infile;
infile = fopen("I4F6.txt", "r");
if (infile == NULL)
printf("Error reading text file\n");
while (TRUE){
nscan= fscanf(infile, "%[^ ] %[^ ] %[^ ] %d%c",
name, surname, phone, &code, &termch);
printf("%s %s %s %d\n", name ,surname, phone, code);
if (nscan == EOF)
break;
if (nscan != 5 || termch != '\n')
printf("Error line\n");
}
return 0;
}
An the text file goes like this, with the name first, then the surname, a phone number that needs to be saved as string and a code.
nikos dimitriou 6911111112 1
maya satratzemi 6933333332 20
marios nikolaou 6910001112 15
maria giannou 6914441112 1
dimitra totsika 6911555111 14
giannis pappas 6911111222 16
nikos ploskas 6911111662 20
But the result i get from this printf is this:
nikos 6911111112 1
maya 6933333332 20
marios 6910001112 15
maria 6914441112 1
dimitra 6911555111 14
giannis 6911111222 16
nikos 6911111662 20
Error line
nikos 6911111662 20
So as you can see it skips all the surnames and produces an error line.
So what should I do to read and store every value seperated with space from the text file into a variable?
Thanks for your time
OP's key problem is using char phone[10];
to store "6911111112"
which needs 11 char
. This all leads to undefined behavior with the unlimited %[^ ]
what should I do to read and store every value separated with space from the text file into a variable?
*scanf()
is difficult to use to detects lines and not get fooled with line endings like "\\r\\n"
. Better to read the line and then parse it and use width limited fields.
Consider using %n
(it stores the scan offset) to detect a proper scan.
char name[9];
char surname[20];
char phone[10+1];
char buf[100];
while (fgets(buf, sizeof buf, infile)) {
int n = 0;
sscanf(buf, " %8[^ ] %19[^ ] %10[^ ]%d %n", name, surname, phone, &code, &n);
// incomplete scan or extra text detected
if (n == 0 || buf[n]) {
printf("Error line\n"); // do not use name, surname, phone, code
break;
}
printf("%s %s %s %d\n", name, surname, phone, code);
}
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.