problem: input and display an integer

for the following code:

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
main() {
    int i;
    do {
        printf("Nhap i: ");
        fflush(stdin);
        scanf("%d", &i);
        printf("%d\n", i);
    }   while (1);
    getch();
}

please tell me how to check if user input is not an integer (with underlined text unchange).
Thanks a lot!
Last edited on
@shadow123: yeah I got it. Thank you :)
Ok now I've got a problem. I have to verify user input. It will be considered invalid if user submit a character or several numbers such as 2, 3. What should I do?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h>
main() {
    int validinput=0;
    int choice;
    printf("Input: ");
    while (validinput==0) {
        fflush(stdin);
        if(scanf("%d", &choice)!=1) {
            printf("Invalid input!");
        } else {
            if(choice<0||choice>5||choice==2||choice==3) {
                printf("Invalid input!");
            } else {
                printf("Valid input!");
                validinput=1;
            }
        }
    }
    getch();
}

I found that could help :) Any other idea?
Something along these lines
1
2
3
4
5
6
7
char line[128]
gets(line);
i =atoi(line);
if(i == 0 && strlen(line) > 1 && line[0] != '0')
{
//Not valid int
}
Topic archived. No new replies allowed.