简体   繁体   English

C - fscanf混合数和静态文本

[英]C - fscanf Mixed Numbers and Static Text

I am trying to read a file formatted in this general way: 我试图读取以这种一般方式格式化的文件:

Text Description: 12
Description2: 1
More descriptive things: 6

And I would like to read the numbers 12, 1, and 6 into variables. 我想把数字12,1和6读成变量。

I have tried code like this: 我试过这样的代码:

fscanf(fptr, "Text Description:%d",&desc1);
fscanf(fptr, "Description2:%d",&desc2);
fscanf(fptr, "More descriptive things:%d",&desc3);

But for some reason only the first variable is being populated. 但由于某种原因,只有第一个变量被填充。 Does anyone know why this is the case? 有谁知道为什么会这样?

Add space at the beginning of the string format to avoid the new line problems 在字符串格式的开头添加空格以避免新行问题

fscanf(fptr, " Text Description:%d",&desc1);
fscanf(fptr, " Description2:%d",&desc2);
fscanf(fptr, " More descriptive things:%d",&desc3);

You aren't reading the newline once you've processed the 12, so the other two calls are finding that instead of the string or integer and therefore failing. 处理完12后,您不会读取换行符,因此其他两个调用是查找而不是字符串或整数,因此失败。 You can use a space in the next fscanf call (which consumes all whitespace characters preceding the string you want to match). 您可以在下一个fscanf调用中使用空格(它会消耗您要匹配的字符串前面的所有空白字符)。 Alternatively you can consume it with a call to fgetc , as long as each line ends immediately with a linefeed, eg 或者,您可以通过调用fgetc来使用它,只要每行直接以换行符结束,例如

fscanf(fptr, "Text Description:%d",&desc1);
fgetc(fptr); // drop the next character
fscanf(fptr, "Description2:%d",&desc2);

Dropping all stream input after the integer and up to the next '\\n' can be done with a loop instead: 在整数之后删除所有流输入,直到下一个'\\ n',可以使用循环来完成:

while (fgetc(fptr) != '\n')
   ;

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

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