如何将输入作为字母或整数?

How to get an input as either a letter or an integer?

我正在尝试制作一个科学计算器。我有几种不同的操作,用户需要输入一个字符来指示要使用的运算符。

这个简单计算器的运算列表是:

正弦 (S)、余弦 (N)、正切 (T)、指数 (E) 功率 (W)、绝对值 (A)、阶乘 (F) 加 (+)、减 (-)、除 (/)、乘 (*)、模 (%) 退出 (Q)

因此,例如,应用程序将如下所示:

输入用户输入:30
输入用户输入:S
Sin(30) = 0.5

我需要接受用户的输入,并允许他们输入整数或字母。我怎样才能做到这一点。我可以同时得到一个整数和一个字母吗?

你应该在接受输入时验证用户输入,你可以通过验证输入的 ASCII 值来做到这一点。一种方法是以字符串形式获取输入,然后将其解析为标记。

一种方法是将 scanf%sfgets 一起使用。

  1. 使用fgets获取输入:

    fgets(buffer,sizeof(buffer),stdin);
    

    请注意 fgetsbuffer 中包含 \n 字符。您可能必须将其删除。

  2. 使用sscanf等函数解析buffer。此函数returns从缓冲区中成功提取的项目数:

    if(sscanf(buffer,"%d",&num)==1) //Try to extract a number
        //Extraction successful!
    

    否则,检查 buffer(buffer[0]) 的第一个字符是否是有效字符。也可以进行检查以测试 buffer 的长度。

你可以驯服strtol:它有输出参数endptr,如果它成功解析整数,将设置为行尾。 @CoolGuy 已经解释了其余代码。

#include <stdio.h>
#include <string.h>

#define MAXINPUTLEN     32

int main() {
    char input[MAXINPUTLEN];
    char* eol;
    char* end;
    long l1;

    do {
        fputs("Enter user input: ", stdout);

        if(fgets(input, MAXINPUTLEN, stdin) == NULL)
            break;

        /* User entered empty string, exit the loop */
        if(input[0] == '\n')
            break;

        eol = strchr(input, '\n');
        if(eol == NULL) {
            /* Input string is too long, warn user, ignore the rest, and retry */
            fputs("Input is too long and may be truncated, please retry!\n", stderr);
            while(fgetc(stdin) != '\n');
            continue;
        }

        /* Remove newline character (should be the last) */
        *eol = '[=10=]';

        l1 = strtol(input, &end, 10);
        if(end == eol) {
            /* User entered integer */
            printf("You have entered an integer: %ld\n", l1);
        }
        else {
            /* User entered a string */
            printf("You have entered a string: %s\n", input);
        }

        /* Read input unless user do not input an empty string */
    } while(input[0] != '\n');  
}