如何检查用户是否提供了正确的数据类型

时间:2016-02-18 06:42:11

标签: c++ c type-conversion

假设我有一个整数类型'a'的变量

现在生病了要求用户在输入后输入输入我想检查天气他输入的整数类型或其他任何东西

对于上述问题,我该怎么做

3 个答案:

答案 0 :(得分:4)

以字符串形式阅读,并尝试使用std::stoistrtol转换为整数。

或者尝试读取整数,然后std::cin GridView读取(或实际读取输入时,流可以用作check the status),或boolean expressions }返回。

注意在C ++和C之间处理这类事情的方法有何不同?这就是为什么在提问时使用正确的语言标签很重要。不同的语言有不同的解决方案。

答案 1 :(得分:1)

如果您正在使用scanf,请检查它的返回值。这个答案适用于C.

  

成功时,scanf返回成功读取的项目数。如果发生匹配故障,此计数可以匹配预期的读数或更少,甚至为零。如果在成功读取任何数据之前输入失败,则返回EOF。

所以,示例程序:

#include <stdio.h>

int main()
{
    int a;
    if (scanf("%d", &a) == 1) {
        printf("Is integer\n");
    } else {
        printf("Not an integer.\n");
    }
    return 0;
}

另见:Check if a value from scanf is a number?

答案 2 :(得分:-1)

C ++有一个可以使用的内置运算符the typeid operator

#include <typeinfo>

main(){
int a;
cin>>a;
if(typeid(a)==typeid(int))   //check whether your variable is integer type
//your code
}

注意:这仅适用于C ++,而不适用于C。