【问题标题】:Read a single user input using scanf and convert it into appropriate data type使用 scanf 读取单个用户输入并将其转换为适当的数据类型
【发布时间】:2020-12-09 15:22:45
【问题描述】:

我有一个程序可以读取用户输入:

char c;
scanf("%c", &c);

然后检查是否为数字:

if(isdigit(c)) {
    int f = atoi(c);
    return f;
}

switch(c) {
    case 'q':
        exit(1);
        break;
    ...
}
...

示例程序:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main() {
    char c;
    scanf("%c", &c);

    if(isdigit(c)) {
        int f = atoi(&c);
        printf("f: %d\n", f);
        return f;
    }

    switch(c) {
        case 'q':
            printf("q\n");
            return -1;
            break;
    }

    return 0;
}

但是,例如,当我输入 10 时,输入变为 1 和 0 和 \n。我想要 10。例如,如何阅读“10”、“100”和“4”以及“q”等其他字符?

【问题讨论】:

  • 可以读取字符串
  • 请记住,atoi 的参数是一个以 null 结尾的字符串。它也没有任何验证。使用例如strtol 用于带有验证的转换函数。
  • @ForceBru 如果我读取一个字符串,那么如何将它转换为浮点数并使用 switch 语句?
  • @Someprogrammerdude 感谢您的提醒。我刚开始学习C,我知道scanf和atoi等的衰落。这只是开始。再次感谢!
  • @pointersarehard,您可以使用strcmp 代替switch 语句

标签: c input


【解决方案1】:

char 变量只能保存一个字符。因此,如果您想在 char 变量中包含多个字符(数字也是字符),则必须使用 stringchar VARIABLE[size] 。例如:char variable[10] 最多可以保存 10 个字符。但是你不能再以这种方式使用isdigit()。相反,您必须使用循环来检查字符串的每个字符。

【讨论】:

    猜你喜欢
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    • 2015-06-08
    • 2017-05-02
    • 2019-05-16
    • 2019-09-12
    • 2023-01-17
    • 1970-01-01
    相关资源
    最近更新 更多