c++ - 使用 fscanf 从文件中读取字符

标签 c++ c file char scanf

我在使用 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/

相关文章:

Java - 从文本文件中读取对象

javascript - <input type ="file"/> 点击表单域部分时在FireFox3中打开文件浏览窗口?

c++ - C++ 中的 .dat ASCII 文件 I/O

c++ - 共享库有一些问题

c - 在 ARM Neon 汇编中使用 C 变量

c - 左值需要作为一元 '&' 操作数

c - 如何在最小的 linux 内核环境中启动进程?

c++ - 具有未知变量类型的文件的最佳数据结构

c++ - Profiler 表明函数调用开销是正常语句的 10 倍

C++,为矩阵乘法重载 *