3

I have a problem in this code when I enter a string, instead of integer. How do I check if the user has entred a character instead of integer? (I would like to put out a message to the user saying you should use numbers, not characters)

ALSO: if you find anything in this code I can improve, please help me! (I am new to C)

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main () {

    int secret, answer;

    srand((unsigned)time(NULL));

    secret = rand() % 10 + 1;

    do {
        printf ("Guess a number between 1 and 10");
        scanf ("%d",&answer);
        if (secret<answer) puts ("Guess a higher value");
        else if (secret>answer) puts ("Guess a lower value");
    } while (secret!=answer);

    puts ("Congratz!");
    return 0;
}
user1431627
  • 815
  • 3
  • 13
  • 30

5 Answers5

4

scanf returns the number of matches is finds. In your case it will return 1 if it readss a number. 0 if it can't read a number in:

if(scanf ("%d",&answer) != 1){
    puts("Please input a number");

    // Now read in the rest of stdin and throw it away.
    char ch;
    while ((ch = getchar()) != '\n' && ch != EOF);

    // Skip to the next iteration of the do while loop
    continue;
}
Paul
  • 139,544
  • 27
  • 275
  • 264
3

Read the input as a string (char[] and %s), check all characters are (isdigit()) digits (possibly allowing for a '+' or '-' as first character) and use atoi() to convert to int.

hmjd
  • 120,187
  • 20
  • 207
  • 252
0

You should write a function that returns true if and only if every character in the string is a digit, and false otherwise.

char * in_str;
int answer;

...

sscanf("%s", in_str);

if (!is_number(in_str)) {
  printf("Please put in a number, not a letter");
} else {
  answer = atoi(in_str);
}

...

You need to implement the is_number function

Bill
  • 2,319
  • 9
  • 29
  • 36
0

Since you can't assume that the user's input is an integer, have scanf() accept a string instead. Then try convert that string with strtol(); that will return 0 if the input was not an integer.

chrisaycock
  • 36,470
  • 14
  • 88
  • 125
0

Read the input as a string with fgets and then use strtol to check the input. strtol contrary to atoi is able to do error checking.

ouah
  • 142,963
  • 15
  • 272
  • 331