tacoofdoomk
tacoofdoomk

Reputation: 53

Read in an int in c and ignore anything else

I am trying to read in an int using scanf() in order to use for later calculations but I am trying to get it to discard anything after the int.

Essentially I want to be able to prompt the user to answer a question such as

What is 3 + 5?

and for the user to be able to enter either 8 or 8 dog or anything of that nature and it be treated the same. I have tried using scanf("%*[^\n]\n"); however this causes issues elsewhere in the program by causing other prompts to not display correctly. I should also that the value read in (the 8 in this case) is needed for other calculations and I need to have the dog portion removed as it causes issues later on in the program as well.

Sample Code to clarify issue in comments

printf("What is %d %c %d ", a, oper, b);
fgets(line, sizeof(line), stdin);
errno = 0;
num = strtol(line, NULL, 10);
if (num == answer)
    {
    printf("Correct!");
    right++;
    }
else
    {
    printf("Wrong!");
    }
printf("\n");

    if (errno != 0)
{
    printf("Invalid input, it must be just a number \n");
}

basically this part grades a math question the user entered

Upvotes: 0

Views: 287

Answers (1)

dbush
dbush

Reputation: 223739

Using scanf can be tricky when trying to read input in this manner. I'd recommend reading in a whole line using fgets then using strtol to convert the result to a number.

char line[100];
long int num;
fgets(line,sizeof(line),stdin);
errno = 0;
num = strtol(line, NULL, 10);
if (errno != 0) {
    printf("%s is not a number!\n", line);
}

EDIT:

What you have looks good, although as chux pointed out in the comments, it isn't detecting a non-numerical value correctly.

This should do it:

int main()
{
    int a, b, answer, right;;
    char oper, *p;
    char line[100];
    long int num;

    right=0;
    a=3, b=5, oper='+', answer=8;
    printf("What is %d %c %d ", a, oper, b);
    fgets(line, sizeof(line), stdin);
    errno = 0;
    num = strtol(line, &p, 10);    // p will point to the first invalid character
    if (num == answer)
    {
        printf("Correct!");
        right++;
    }
    else
    {
        printf("Wrong!");
    }
    printf("\n");

    if (errno != 0 || p == line)
    {
        printf("Invalid input, it must be just a number \n");
    }
}

Upvotes: 2

Related Questions