Check if User Inputs a Letter or Number in C

后端 未结 7 1530
终归单人心
终归单人心 2020-12-03 15:22

Is there an easy way to call a C script to see if the user inputs a letter from the English alphabet? I\'m thinking something like this:

if (variable == a -          


        
7条回答
  •  眼角桃花
    2020-12-03 16:08

    isalpha() will test one character at a time. If the user input a number like 23A4, then you want to test every letter. You can use this:

    bool isNumber(char *input) {
        for (i = 0; input[i] != '\0'; i++)
            if (isalpha(input[i]))
                return false;
        return true;
    }
    
    // accept and check
    scanf("%s", input);  // where input is a pointer to a char with memory allocated
    if (isNumber(input)) {
        number = atoi(input);
        // rest of the code
    }
    

    I agree that atoi() is not thread safe and a deprecated function. You can write another simple function in place of that.

提交回复
热议问题