我有以下程序:
int main(int argc, char *argv[])
{
int a, b;
char c1, c2;
printf("Enter something: ");
scanf("%d",&a); // line 1
printf("Enter other something: ");
scanf("%d", &b); // line 2
printf("Enter a char: ");
scanf("%c",&c1); // line 3
printf("Enter another char: ");
scanf("%c", &c2); // line 4
printf("Done"); // line 5
system("PAUSE");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
正如我在C书中读到的那样,作者说scanf()在缓冲区中留下了一个新的行字符,因此,程序不会在第4行停止供用户输入数据,而是将新行字符存储在c2中并移至第5行.
是对的吗?
但是,这只发生在char数据类型中吗?因为我没有int在第1,2,3行中看到数据类型的这个问题.是不是?
#include <stdio.h>
int main(int argc, char* argv[]) {
char c;
scanf(" %c", &c);
printf("%c\n", c);
return 0;
}
[root@test]# ./scanf
a
a
[root@test]# ./scanf
h
h
Run Code Online (Sandbox Code Playgroud)
似乎总是匹配空间是否存在,为什么?
我读过周围的内容,每个人都说在扫描单个字符时使用" %c",因为输入流的开头可能有空格。
好吧,公平。但这仅适用于所述输入流中的第一个字符吗?如果我现在扫描由许多连续字符组成的字符串中的单个字符怎么办?(例如:abcdef)
" %c"现在用作格式说明符不会把事情弄乱吗?
这是我的 C 代码:
\n\n#include "stdio.h"\n\nint main()\n{\n int minx, x;\n\n printf("Enter two ints: ");\n scanf( "%d-%d", &minx, &x);\n\n printf("You wrote: minx is %d x is %d", minx, x);\n}\nRun Code Online (Sandbox Code Playgroud)\n\n当输入为5-3或5- 3时,输出为You write: minx is 5 x is 3这是有道理的。但是,当输入为5 -3或5 - 3或6 -4时,输出为You write: minx is 5 x is 8。我期望-跳过空格,所以我期望其他输入的minx为5,x为3、6和4 。-当in%d-%d …