scanf要求两个值而不是一个

时间:2014-11-27 10:45:24

标签: c scanf

当我编译这段代码时,当我选择A时,它会导致scanf要求两次值。我在这里缺少什么?

这不是第一次遇到这种情况,所以我怀疑我没有抓住scanf的基本内容。

#include <stdio.h>
#include <stdlib.h>

int main()
{

char choice;
printf("1. 'enter 'A' for this choice\n");
printf("2. 'enter 'B' for this choice\n");
printf("3. 'enter 'C' for this choice\n");

scanf("%c", &choice);

switch (choice)
{
case 'A':
    {
        int a =0;
        printf("you've chosen menu A\n");
        printf("enter a number\n");
        scanf("%d\n", &a);
        printf("%d\n", a);
    }
break;
case 'B':
printf("you've chosen B\n");
break;
case 'C':
printf("you've chosen C\n");
break;
default:
printf("your choice is invalid\n!");
break;
}

return 0;

}

4 个答案:

答案 0 :(得分:6)

scanf("%d\n", &a);应为scanf("%d", &a);

另请阅读Related question

在前一种情况下,在读取整数并存储到a之后,scanf的参数字符串不会耗尽。查看\n,scanf将消耗它看到的所有空格(换行符,制表符,间隔等)(并将保持阻塞状态),直到遇到非空白字符为止。遇到非空白字符scanf将返回。

学习:不要在scanf中使用空格,换行符等作为尾随字符。如果空格字符位于参数字符串的开头,则scanf仍可以跳过任意数量的空格字符,包括零字符。但是当空白是一个尾随字符时,它会占用你的新行字符,除非你输入一个非空白字符并点击返回键。

答案 1 :(得分:4)

只需从scanf("%d\n", &a);中删除换行符,它就不会要求输入值两次

答案 2 :(得分:0)

scanf("%d", &a);

扫描时删除换行符

答案 3 :(得分:0)

// the trailing '\n' in the scanf format string 
// is what is causing the dual inputs

// the returned value from I/O statements (I.E. scanf)
// needs to be checked to assure operation was successful

#include <stdio.h>
#include <stdlib.h>

int main()
{

    char choice;
    printf("1. 'enter 'A' for this choice\n");
    printf("2. 'enter 'B' for this choice\n");
    printf("3. 'enter 'C' for this choice\n");

    // note 
    //    leading ' ' in format string to consume leading white space 
    //    and no trailing '\n'
    if( 1 != scanf(" %c", &choice) ) 
    { // then, scanf failed
        // handle error condition
        perror("scanf failed for choice");
        exit(EXIT_FAILURE);
    }

    // implied else, scanf successful

    switch (choice)
    {
        case 'A':
        { // braces needed due to variable declaration
            int a = 0; // corrected ':' to ';'
            printf("you've chosen menu A\n");
            printf("enter a number\n");

            // note 
            //    leading ' ' in format string to consume leading white space 
            //    and no trailing '\n'
            if( 1 != scanf(" %d", &a) ) 
            { // then scanf failed
                // handle error condition
                perror("scanf failed for number");
                exit(EXIT_FAILURE);
            }
            // implied else, scanf successful
            printf("%d\n", a);
        }
        break;

        case 'B':
            printf("you've chosen B\n");
        break;

        case 'C':
            printf("you've chosen C\n");
        break;

        default:
            printf("your choice is invalid\n!");
        break;
    } // end switch

    return 0;

} // end function: main