简体   繁体   中英

Distinguishing if int or char / string from user input

I'm trying to read input from the user. I'd like to distinguish if the input provided is an int, a char or string.

I tried approaching this with scanf_s, but this didn't quite work. Is there a way to take input from the user, and tell if this is an integer, char, or string?

This is what I had so far.

void CheckIfInt()
{
  char returnValue = 0;

  //loop until we are given a valid input
  while(true)
  {
    scanf_s("%c", &returnValue);
    scanf_s("%C");

    if(isdigit(returnValue))
    {
      //Do something
      break;
    }

    else if(returnValue == 'a')
    {
      //Do something else
      break;
    }
  }
}

First thing you should do is to not use an integer pointer but rather a char pointer. This makes it easier to look at the entire input one byte at a time. So your code should look like this:

void ReadInteger(char* value, bool isX) { ... }

The next part depends on what you are looking to do, either you want to read an entire line as one input or read something until you encounter a space character. I will assume the later, which comes back to your question.

How to tell if you just read a char

int isChar(char *value) {
    return value != NULL && strlen(value) == 1 && isalpha(value[0]);
}

How to tell if you just read an integer

int isInteger(char *value) {
    int ans = 0;
    if (value != NULL && strlen(value) > 1) {
        while (*value && isdigit(*value)) {
            value++;
        }
        ans = (value == NULL);
    }
    ans;
}

How to tell if you just read a string

I'm feeling lazy, so this will do:

int isString(char *value) {
    return !isChar(value) && !isInteger(value);
}

Note that the integer checking method tells if the user only typed in numbers, but doesn't tell you if that number will fit in a 32bit integer. If you want this effect, you can easily modify the code to achieve this

You can read the input into a character array by using fgets and then, parse it using sscanf . You can look at the character array to see what type of data it is. If you provide a sample fo input, I can show you the code.

This should help. You can manipulate the code.

int myNum;
char myTerm;
if(scanf("%d%c", &myNum, &myTerm) != 2 || myTerm != '\n')
    printf("failure\n");
else
    printf("valid integer followed by enter key\n");

reason : myNum will always contain an integer because it's an int

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM