4

在这段代码中,scanf 请求了两次,我不确定是什么原因导致它这样做。

int t;
for(t = 0;t<5;t++)
{
    //scanf requests twice for some reason
    scanf("%s ",input);
    fprintf(fp,"%s ", input);
    printf("%d Word(s)\n", (t+2));
}

输出是(引号中的单词由用户输入)

"hello"
"world"
1 Word(s)
"how"
2 Word(s)
"are"
3 Word(s)
"you"
4 Word(s)
"lostword"
5 Word(s)

"hello world how are you "

将归还给我并保存到文件中。

4

1 回答 1

5

删除 scanf 中的空格。

改变:

scanf("%s ",input);

至:

scanf("%s",input);

由于空间的原因,scanf 会不断跳过空白字符,直到它读取到不是空白的内容(在读取一个字符串之后%s)。

于 2012-12-13T22:50:00.753 回答