如何在C中对单个字符进行扫描在C中:我试图从用户那里获得charscanf当我运行该程序时,不要等待用户输入任何内容.这是代码:char ch;printf("Enter one char");scanf("%c", &ch);printf("%c\n",ch);为什么不起作用?
3 回答
墨色风雨
TA贡献1853条经验 获得超6个赞
%c
scanf
scanf(" %c", &c);
scanf
%c
侃侃无极
TA贡献2051条经验 获得超10个赞
scanf()
scanf()
#include <stdio.h>int main(void){ char ch1, ch2; scanf("%c", &ch1); /* Leaves the newline in the input */ scanf(" %c", &ch2); /* The leading whitespace ensures it's the previous newline is ignored */ printf("ch1: %c, ch2: %c\n", ch1, ch2); /* All good so far */ char ch3; scanf("%c", &ch3); /* Doesn't read input due to the same problem */ printf("ch3: %c\n", ch3); return 0;}
scanf()
abc
int
scanf("%d", &int_var);
abc
#include <stdio.h>int main(void){ int i; while(1) { if (scanf("%d", &i) != 1) { /* Input "abc" */ printf("Invalid input. Try again\n"); } else { break; } } printf("Int read: %d\n", i); return 0;}
scanf()
fgets()
#include <stdio.h>int main(void){ int age; char name[256]; printf("Input your age:"); scanf("%d", &age); /* Input 10 */ printf("Input your full name [firstname lastname]"); fgets(name, sizeof name, stdin); /* Doesn't read! */ return 0;}
fgets()
scanf()
fgets()
#include <stdio.h>int main(void){ char line[256]; char ch; if (fgets(line, sizeof line, stdin) == NULL) { printf("Input error.\n"); exit(1); } ch = line[0]; printf("Character read: %c\n", ch); return 0;}
fgets()
char line[256];if (fgets(line, sizeof line, stdin) == NULL) { printf("Input error.\n"); exit(1);}line[strcpsn(line, "\n")] = 0; /* removes the trailing newline, if present */
- 3 回答
- 0 关注
- 666 浏览
添加回答
举报
0/150
提交
取消