【发布时间】:2015-06-15 02:09:10
【问题描述】:
在编写算术表达式简化器时,我刚刚观察到这种奇怪的行为。重新创建了以下问题:
#include <stdio.h>
int main(void)
{
int n, i;
char s[200];
for(i=0;i<2;i++){
if(scanf("%d", &n) == 1)
{
printf("%d\n", n);
} else {
scanf("%s", s);
printf("%s\n", s);
}
}
return 0;
}
如果输入是5+10,则在n 中读取5,在s 中读取10。但是,对于其他符号,即5-10,它在n 中读取5,在s 中读取-10,这是预期的输出。
我的问题是:哪些 C 功能导致了这种情况?检查:gcc 版本 4.8.2 和 ideone。
编辑
解决了 char by char 读取整数的问题。感谢大家的时间。 :)
如果有人感兴趣:http://ideone.com/rOPyQD
【问题讨论】:
-
看看scanf手册页,特别是格式字符串的解释。
-
@Jens 也许我还不够好,无法找到我的答案。以前和现在阅读它。 :(
-
@user3121023 亲爱的先生,这个程序只需要两个输入,5+10 或 5-10。没有理由在 s 中不扫描任何内容。
-
"+10" -->
10inscanf("%d", &n)。scanf("%s", s);从未被执行。 -
@chux 我怎么能错过。也许需要一些睡眠。谢谢。
标签: c