c - How to use fscanf, care about endofline? -
i want read int file
the first line composed of 1 int , second of 2
ie
1 2 3 if
fscanf(file, "%d \n %d %d", &a, &b, &c); i obtain correctly 3 numbers if put numbers on same line in file ie 1 2 3
i obtain same result (and that's not want)
i want know : how force user go new line in file ?
edit : seems unclear (i'm sorry that) want file
1 2 3 produce result :
a = 1 b = 2 c = 3 and file
1 2 3 produce either error or
a = 1 b = 0 c = 0
fscanf(file, "%d", ...); first scans , discard white space before scanning int characters. in scanning white-space, both ' ' , '\n' treated same, using '%d' loses end-of-line.
fscanf(file, "\n", ...); , fscanf(file, " ", ...); same thing: scan , discard any white space. using "\n" not scan '\n'.
code use fscanf(file, "%d%*1[\n]%d %d", &a, &b, &c) == 3, find '\n' after a, additional '\n' lurking in other places.
the way using scanf() family detect '\n' involves using '%c' or '%[]' or '%n'. easier use fgets() , parse sscanf() or strtol().
int read1and2int(file *stream, int *a, int *b, int *c) { char buf[100]; int n; if (fgets(buf, sizeof buf, stream) == null) return eof; int count = sscanf(buf,"%d %n", a, &n); // non-numeric or data if (count != 1 || buf[n]) return 0; if (fgets(buf, sizeof buf, stream) == null) return 1; count = sscanf(buf,"%d%d %n", b, c, &n); // non-numeric or data if (count != 2 || buf[n]) return 1; return 3; }
Comments
Post a Comment