输入字符而不是整数

时间:2015-12-15 20:58:59

标签: c scanf

我使用do-while循环将菜单打印到屏幕上。而且我将选择作为整数阅读。问题在于,如果用户输入一个角色,程序就会爆炸。我怎么能避免这种情况?

#include <stdio.h>
int menu() {            // prints the main menu of labs///
    int choice;
    printf("1)Lab 5 ( Repetetitions ).\n2)Lab 10 ( Passing 1D-Arrays to functions ).\n3)GPA Calculation.\n4)EXIT.\n\nEnter your choice: ");
    scanf("%d", &choice);
    return choice;
}

int main() {
    int choice;

    do {

        choice = menu();
        if (choice != 4) {

            if (choice == 1)
                //lab5(choice);

            else if (choice == 2)
                //lab10(choice);


            else if (choice == 3)
                //  lab11(choice);
            else
                printf("invalid choice\n");
        }

    } while (choice != 4);
    return 0;
}        

3 个答案:

答案 0 :(得分:2)

这应该对你有用,你需要检查scanf的返回值

int menu() {            // prints the main menu of labs///
    int choice;
    printf("1)Lab 5 ( Repetetitions ).\n2)Lab 10 ( Passing 1D-Arrays to functions ).\n3)GPA Calculation.\n4)EXIT.\n\nEnter your choice: ");
    if(scanf("%d", &choice) == 1)
    {
        return choice;
    }
    else
    {
        return 0;
    }
}

答案 1 :(得分:0)

scanf()(和函数族)返回来自输入缓冲区的成功转换次数,如果转换(%d)失败,则函数返回0(或EOF)。在这种情况下,无法从缓冲区中删除无法转换的字符,这就是无限循环发生的原因,转换始终失败。

我在scanf调用后使用此method刷新输入缓冲区,程序按预期运行。

Run the program online(不知道这会持续多久)

void flushInput(){
  int c;
  while((c = getchar()) != EOF && c != '\n')
        /* discard */ ;  
}

int menu() {            // prints the main menu of labs///
    int choice;
    printf("1)Lab 5 ( Repetetitions ).\n2)Lab 10 ( Passing 1D-Arrays to functions ).\n3)GPA Calculation.\n4)EXIT.\n\nEnter your choice: ");
    if(scanf("%d", &choice) != 1){
        flushInput();
        return 0;
    }else{
        flushInput();
        return choice;
    }
}

答案 2 :(得分:0)

/*USE This Code*/  
#include <stdio.h>
#include <stdlib.h>
void orderAsk(int orderStorage[1]);
int main()
{     
    int orderStorage[1];
    orderAsk(orderStorage);
    printf("%d",orderStorage[0]);
    return 0;
}

void orderAsk(int orderStorage[1]){
    int d;
    d = scanf("%d", &orderStorage[0]);
    if ( d!= 1) {
        system("cls");
        fflush(stdin);
        printf("Error! Re-Enter\n");
        orderAsk(orderStorage);
    }
}