我在使用 fscanf 函数时遇到问题:( 我需要从文件中读取一系列字符,例如“a b c d”(字符由空格分隔)。
但它不起作用:( 我该如何阅读它们? (
我尝试打印它,但结果不正确。我想,这是因为空间。我真的不知道为什么它不起作用。
请告诉我,数组访问有什么问题?
最佳答案
来自cplusplus.com :
The function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none).
那么如果您的代码是:
while ( fscanf(fin,"%c", &array[i++]) == 1 );
并且您的文件包含以下字符串:
你好
您的数组
将是:
[h][ ][e][ ][l][ ][l][ ][o]
如果您将代码更改为:
while ( fscanf(fin," %c", &array[i++]) == 1 );
使用相同的文件,您的数组
将是:
[h][e][l][l][o]
无论如何,代码都可以工作:这取决于您想要什么。
无论如何,您应该考虑开始使用 fgets()
+ sscanf()
,例如:
char buff[NUM];
while ( fgets(buff, sizeof buff, fin) )
sscanf(buff,"%c", &array[i++]);
对于单个fscanf()
,缺乏缓冲区管理可能会导致缓冲区溢出问题。
关于c++ - 使用 fscanf 从文件中读取字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21243094/