C:scanf函数对于char未正常工作 [英] C: scanf for char not working as expected

查看:121
本文介绍了C:scanf函数对于char未正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近跑在我的电脑的C程序。它有一个for循环中,一些焦炭d被扫描。 for循环运行3次。在每个运行它打印运行的计数,然后扫描炭d的值。程序如下:

I was recently running a c program in my PC. It have a for loop in which some char d is scanned. The for loop runs for 3 times. During each running it prints the the count of running and then scans the value of char d. The program is as follows

#include<stdio.h>

int main(){
    int f;
    char d;
    for(f=0;f<3;f++){
        printf("Choice %d\n", f);
        scanf("%c", &d);
    }
    return 0;
}

现在的麻烦是,当我运行程序时,为跳过scanf函数一部分,当f为1。
现在,如果我改变了code如下:

Now the trouble is that when I run the program, the for skips the scanf part when f is 1. Now if i changed the code as follows

#include<stdio.h>

int main(){
    int f;
    int d;
    for(f=0;f<3;f++){
        printf("Choice %d\n", f);
        scanf("%d", &d);
    }
    return 0;
}

现在该程序工作正常。并为循环的每个迭代执行scanf函数。

Now the program works fine. and scanf is executed for every iteration of for loop.

什么似乎是这里的问题?我的意思是,当d为类型诠释它工作正常,但是当d为类型的字符就不能正常工作。

What does seem to be the problem here? I mean when d is of type int it works fine, but when d is of type char it does not work correctly.

推荐答案

您必须修改

scanf("%c", &d);

scanf(" %c", &d);
       ^
       |

另外, scanf()的将考虑pviously进入了$ P $ ENTER 键preSS。

Otherwise, scanf() will consider the previously entered ENTER key press.

请注意:


  1. <大骨节病> ENTER 键preSS生成一个 \\ n ,这是一个vaild输入% ç格式说明。前%C 添加一个空格告诉 scanf()的忽略所有前导空格样的投入(包括previously存储 \\ n ),并读标准输入的第一个非空白字符。

  1. ENTER key press generates a \n, which is a vaild input for %c format specifier. Adding a space before %c tells scanf() to ignore all leading whitespace-like inputs (including that previously stored \n) and read the first non-whitespace character from stdin.

至于与的情况下,%d个格式说明,它消耗的(而忽略)扫描数值输入之前的任何前导空格般的投入,所以第二情况下不会受到任何的问题。

As for the case with %d format specifier, it consumes (and ignores) any leading whitespace-like inputs before scanning for numeric inputs, so the second case does not suffer any issues.

这篇关于C:scanf函数对于char未正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆