假设我有一个整数类型'a'的变量
现在生病了要求用户在输入后输入输入我想检查天气他输入的整数类型或其他任何东西
对于上述问题,我该怎么做
答案 0 :(得分:4)
以字符串形式阅读,并尝试使用std::stoi
或strtol
转换为整数。
或者尝试读取整数,然后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;
}
答案 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。