Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用fscanf时发现额外的空白_C - Fatal编程技术网

使用fscanf时发现额外的空白

使用fscanf时发现额外的空白,c,C,我有一个文件: hello:12312 Bye:333 Hey:22 所以我用fscanf读了它 FILE *file = fopen( argv[1], "r" ); if ( file == 0 ) { printf( "Could not open file\n" ); } else { while(fscanf(file, "%[^:]:%d", wor

我有一个文件:

hello:12312
Bye:333
Hey:22
所以我用fscanf读了它

 FILE *file = fopen( argv[1], "r" );

        if ( file == 0 )
        {
            printf( "Could not open file\n" );
        }
        else
        {

            while(fscanf(file, "%[^:]:%d", word, &integer) != EOF)
            {
                printf("word: %s, integer: %d\n", word, integer);
            }

            fclose( file );
        } 
这就是我得到的:

word: hello, integer: 12312
word:
Bye, integer: 333
word:
Hey, integer: 22

显然,除了第一个单词之外,还有一个额外的空格,为什么会发生这种情况?

%[^::][/code>将接受行尾。如果要跳过将前导空格放入
word
中,请尝试:

 " %[^:]:%d"

在字符串格式的开头添加空格
“%[^:::%d”
。这将避免scanf中的换行问题

 while(fscanf(file, " %[^:]:%d", word, &integer) != EOF)

因为使用*scanf()函数读取整数时,不会使用以下换行符。

From:

在尝试分析输入之前,[、c和n以外的所有转换说明符都会使用并丢弃所有前导空格字符

\n
将在
%d”
之后保留输入流

要更正此错误,请在format speicifer中添加前导空格以跳过空白:

while(fscanf(file, " %[^:]:%d", word, &integer) == 2)
{
}
!=EOF
更改为
==2
,以防止接受格式为
“hello:”
“hello”
的行