为什么scanf会跳过' \ n'在freopen功能?

时间:2014-03-11 14:43:37

标签: c scanf freopen

我正在使用 freopen 功能来读取文件。但是当我使用 scanf 语句扫描整数时,它会跳过'\ n'字符。我怎样才能避免通过scanf跳过'\ n'

3 个答案:

答案 0 :(得分:1)

建议发布更多编码目标,以便我们建议如何避免“不跳过\ n”。

scanf()不会跳过'\n'。选择格式指定"%d"直接scanf(),以跳过领先的白步 - 包括'\n'

如果想要使用scanf()而不是跳过'\n',请使用"%[]""%c"等格式说明符。或者,尝试使用fgets()fgetc()的新方法。

如果代码必须使用scanf()而不是在扫描'\n'时跳过int,请提供以下建议:

char buf[100];
int cnt = scanf("%99[-+0123456789 ]", buf);
if (cnt != 1) Handle_UnexpectedInput(cnt);

// scanf the buffer using sscanf() or strtol()
int number;
char sentinel
cnt = sscanf(buf, "%d%c", &number, &sentinel);
if (cnt != 1) Handle_UnexpectedInput(cnt);

替代方案:首先使用所有前导空格,寻找\n

int ch;
while ((ch = fgetc(stdin)) != '\n' && isspace(ch));
ungetc(ch, stdin);
if (ch == '\n') Handle_EOLchar();
int number;
int cnt = scanf("%d", &number);
if (cnt != 1) Handle_FormatError(cnt); 

答案 1 :(得分:0)

你不能!但不要担心,有一些解决方法。

解决方法:

一次读取一行输入(使用fgets),然后使用sscanf扫描整数。

#define LINE_MAX 1000
line[LINE_MAX];
int num;

while (fgets(line, LINE_MAX, fp) != NULL) {
    if (sscanf(line, "%d", &num) == 1) {
        // Integer scanned successfully
    }
}

答案 2 :(得分:0)

xscanf函数将通过DFA处理字符串。它将搜索由 fmt 参数给出的格式,将跳过每个空格字符(空格,\ t,\ n,\ r \ n等)。您可以将这些空格字符插入 fmt 进行匹配。

例如,它是如何跳过的:

#include <stdio.h>
#include <stdlib.h>


int main(int argc, char** argv)
{
    char* s = "1 2 \n 3 4 \n 5 \n \n \n 6";
    int i,c;
    int tot=0;
    while(sscanf(s+tot,"%d%n",&i,&c)){
        printf("'%s':%d,cnt=%d\n",s+tot,i,c);
        tot += c;
    }
    return 0;
}
/*** Output:
'1 2 
 3 4 
 5 


 6':1,cnt=1
' 2 
 3 4 
 5 


 6':2,cnt=2
' 
 3 4 
 5 


 6':3,cnt=4
' 4 
 5 


 6':4,cnt=2
' 
 5 


 6':5,cnt=4
' 


 6':6,cnt=8
'':6,cnt=8
***/