【发布时间】:2014-05-29 14:34:20
【问题描述】:
我使用 scanf 从 stdin 读取输入,因为 scanf 被认为比 cin 快得多。我发现了以下意外行为:
for(int i = 0; i<3; i++) {
scanf("%d ", &t);
printf("The input was %d\n", t);
}
scanf 中的 "%d " 格式应读取整数并忽略其后的空格或换行符。因此预期的输出应该是这样的:
0
The input was 0
1
The input was 1
2
The input was 2
但是我得到以下输出:
0
1
The input was 0
2
The input was 1
有人可以帮我理解这里的行为吗?
【问题讨论】:
-
" %d"而不是"%d "。 -
这类错别字应该记录在
scanf标签wiki中。 -
如果你使用
std::ios_base::sync_with_stdio(false),std::cin的性能应该不会比std::scanf()差。