C++ User enters a non-integer value for integer variable

fts

I am working on program where a list of options is displayed to the user and he would then enter an integer to specify which option he wants to select.Now I have pre-empted the situation where the user might enter an integer value apart from the valid ones. But if he enters any other value, say a character or a string, the program goes into an infinite loop with the list of options being printed infinitely. How can i rectify this? I mean, I should be able to give my user an error when for a predefined integer variable he enters a value that is not an integer.

Any help appreciated. Here is a sample code.

do{
    printf("Select appropriate option.\n");
    printf("Press 1 to do this");
    printf("Press 2 to do that.\n");
    printf("Press 3 to exit the program.\n");
    scanf("%d",&choice);
    if(choice!=1 && choice!=2 && choice!=3)
        printf("You entered an invalid choice. Please enter again.\n");
    switch(choice){
        case 1:
            //do this
             break
        case 2:
            //do that
            break;
        case 3:
            exit(1);
           }}


while(choice!=3);

So basically when a user enters a non-integer value for choice I want the program to notify the user and ask him for another input.

AnT

It cannot be done with direct scanf into an integer variable. Such scanf will not only accept 1.23, it will also accept 1abcde and other inputs. scanf (and other conversion functions) reads as much as it can in accordance with the requested format. It stops when it finds something that does not satisfy format requirements and simply leaves it untouched.

If you want to perform this sort of analysis, you have to read the input as string and then parse and analyze that string manually.

A C-style code sketch (since you insist on C-style code, despite having tagged it as [C++]) might look as follows

char buffer[100]; /* 100 should be enough for everyone :) */
int n = scanf("%s", buffer);
if (n < 1)
  /* ERROR, can't read */;

char *end;
long choice = strtol(buffer, &end, 10); 
if (end == buffer || *end != '\0' || errno == ERANGE)
  /* ERROR, bad format */;

/* ... */

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Setting Integer value in Objective c

분류에서Dev

Trying to switch a direct integer value with a variable in swift

분류에서Dev

C Structure initialization (Array of integers and an integer value)

분류에서Dev

integer variable in awk script

분류에서Dev

Incorrect integer value: '' for column

분류에서Dev

what this integer value means?

분류에서Dev

C call a different function based on a given integer value

분류에서Dev

Is there a way to name an object based on the value of an integer? Objective C

분류에서Dev

Put integer variable in string manually

분류에서Dev

How to put integer value in JLabel?

분류에서Dev

Combining integer and string in array value

분류에서Dev

Using python/pandas to search dataframe rows containing both a user-specified integer and approximated float value

분류에서Dev

Scala Map Integer to (Integer => Integer)

분류에서Dev

C++ basic integer confusion

분류에서Dev

Char to Integer coversion in c++

분류에서Dev

How to tween an integer variable using TweenMax?

분류에서Dev

Integer variable not following while loop conditions

분류에서Dev

In bash, is it possible to use an integer variable in a brace expansion

분류에서Dev

Check whether a factor variable is of type integer or float

분류에서Dev

Insert an integer after some integer in binary file in C

분류에서Dev

How to manage long integer value in url

분류에서Dev

Setting a void pointer's value to an integer

분류에서Dev

The biggest integer value can be represented by double in Java

분류에서Dev

Error in Trigger for incrementing the value with Prefix and Integer.

분류에서Dev

Postgres : Select the maximum integer substring of a column value

분류에서Dev

C++ Function supposed to return Long, returning Integer like value instead

분류에서Dev

How do I convert a double variable to an integer variable?

분류에서Dev

How to input value from user and save in variable wxDev-C++

분류에서Dev

Can not evoke watch command with non-integer time option

Related 관련 기사

  1. 1

    Setting Integer value in Objective c

  2. 2

    Trying to switch a direct integer value with a variable in swift

  3. 3

    C Structure initialization (Array of integers and an integer value)

  4. 4

    integer variable in awk script

  5. 5

    Incorrect integer value: '' for column

  6. 6

    what this integer value means?

  7. 7

    C call a different function based on a given integer value

  8. 8

    Is there a way to name an object based on the value of an integer? Objective C

  9. 9

    Put integer variable in string manually

  10. 10

    How to put integer value in JLabel?

  11. 11

    Combining integer and string in array value

  12. 12

    Using python/pandas to search dataframe rows containing both a user-specified integer and approximated float value

  13. 13

    Scala Map Integer to (Integer => Integer)

  14. 14

    C++ basic integer confusion

  15. 15

    Char to Integer coversion in c++

  16. 16

    How to tween an integer variable using TweenMax?

  17. 17

    Integer variable not following while loop conditions

  18. 18

    In bash, is it possible to use an integer variable in a brace expansion

  19. 19

    Check whether a factor variable is of type integer or float

  20. 20

    Insert an integer after some integer in binary file in C

  21. 21

    How to manage long integer value in url

  22. 22

    Setting a void pointer's value to an integer

  23. 23

    The biggest integer value can be represented by double in Java

  24. 24

    Error in Trigger for incrementing the value with Prefix and Integer.

  25. 25

    Postgres : Select the maximum integer substring of a column value

  26. 26

    C++ Function supposed to return Long, returning Integer like value instead

  27. 27

    How do I convert a double variable to an integer variable?

  28. 28

    How to input value from user and save in variable wxDev-C++

  29. 29

    Can not evoke watch command with non-integer time option

뜨겁다태그

보관