I have a text file following this format:
Thing 1: 0 0 128
Other thing: 255 64 255
Something else: 32 32 8
I intend to add more to this file eventually but the format will remain the same. What I want to do is read everything before the colon into a string and everything after it as an integer. I've tried this:
fscanf((file = fopen("colors.txt", "r")) == NULL){
return -1;
}
fscanf("%s: %d %d %d", colorStr, &r, &g, &b);
while(!feof(file)){
printf("%s: %d %d %d", colorStr, r, g, b);
fscanf(file, "%s: %d %d %d", colorStr, &r, &g, &b);
}
fclose(file);
However, I get this output:
Thing 1:: 0 0 0
0: 0 0 0
0: 0 0 0
128: 0 0 0
And so on. Ideally, the output should read like this:
Thing 1: 0 0 128
Other thing: 255 64 255
Something else: 32 32 8
How can I fix this? The colorStr
, r
, g
, and b
variables were set up earlier in the program.
The problem with your code is that the text contains spaces, which %s
does not allow.
Changing the format string to %[^:]
will fix this problem.
However, the code would remain vulnerable to buffer overrun. Make sure that your format string includes the max size of colorStr
to prevent it:
char colorStr[100];
fscanf(file, " %99[^:]: %d %d %d", colorStr, &r, &g, &b);
Your code uses feof(file)
, which is incorrect. You should put fscanf
into loop header. This would let you remove the duplicate fscanf
call before the loop:
while(fscanf(file, " %99[^:]: %d %d %d", colorStr, &r, &g, &b) == 4) {
printf("%s: %d %d %d\n", colorStr, r, g, b);
}
Note the space in front of the leading %
format specifier. It instructs fscanf
to skip the trailing spaces and/or '\\n'
from the previous line.
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.