简体   繁体   English

C-从格式化的文本文件中读取带有整数的字符串

[英]C - Read string with integers from formatted text file

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. colorStrrgb变量是在程序的前面设置的。

The problem with your code is that the text contains spaces, which %s does not allow. 您的代码的问题是文本包含空格, %s不允许使用空格。

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: 确保您的格式字符串包括colorStr的最大大小,以防止出现这种情况:

char colorStr[100];
fscanf(file, " %99[^:]: %d %d %d", colorStr, &r, &g, &b);

Your code uses feof(file) , which is incorrect. 您的代码使用feof(file) ,这是不正确的。 You should put fscanf into loop header. 您应该将fscanf放入循环标头中。 This would let you remove the duplicate fscanf call before the loop: 这将使您在循环之前删除重复的fscanf调用:

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. 它指示fscanf跳过前一行的尾随空格和/或'\\n'

Demo. 演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM