c 语言如何扫描输入的字符,如何在C中对单个字符进行扫描

首先,避免scanf()..使用它是不值得的痛苦。

中使用空白字符。scanf()如果需要读取更多的输入,会忽略输入流中留下的任意数量的空格字符吗?考虑:#include 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(),但它并不总是像上面那样简单。另一个主要问题是,scanf()如果输入流与格式不匹配,则不会丢弃输入流中的任何输入。例如,如果您输入abc为了int例如:scanf("%d", &int_var);然后abc将不得不阅读和丢弃。考虑:#include 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 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()调用留下的换行符是Read,而fget()在遇到换行符时终止输入读取。

还有许多其他类似的问题scanf()..这就是为什么人们通常建议避免这样做。

那么,还有别的选择吗?使用fgets()函数以下列方式读取单个字符:#include 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()如果iNut缓冲区中有足够的空间,将在换行符中读取。如果它不可取,那么您可以删除它: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 */

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值