简体   繁体   English

接收到错误的数据类型时如何获取正确的数据类型

[英]How to get the correct data type when the wrong data type is received

#include<iostream>
#include<string>
using namespace std;

int main() {
    while (1) {
        int num;
        cin >> num;
        if (typeid(num).name() != "int") {
            cout << "please input integer" << endl;
            continue;
        }
    }
}

When I wrote the code like this, I thought that if the wrong data type was input, the while statement would be executed again by continue , and the variable num would be input again.写这样的代码时,我想如果输入了错误的数据类型, while语句会被continue再次执行,变量num又会被输入。

However, an infinite loop occurs instead.但是,会发生无限循环。 I would be grateful if you could help me with why.如果您能帮助我解释原因,我将不胜感激。

You are not checking whether cin >> num;您没有检查是否cin >> num; succeeds or fails.成功或失败。 And if it does fail, you are not clear() 'ing the error before continuing.如果它确实失败了,那么在继续之前你并不clear()错误。

You can't use typeid() to check for success/failure of >> .您不能使用typeid()来检查>>的成功/失败。 That is not what it is meant for.这不是它的本意。 typeid(num) is evaluated at compile-time, producing a std::type_info that describes int itself. typeid(num)在编译时被评估,产生一个描述int本身的std::type_info An int will always be an int , regardless of what is assigned to num at runtime.无论在运行时分配给num什么,一个int始终是一个int Besides, in your example, typeid(num).name() != "int" will always evaluate as true, since you are comparing a const char* pointer from name() to a string literal that is clearly stored elsewhere in memory, so the two memory addresses don't evaluate as equal.此外,在您的示例中, typeid(num).name() != "int"将始终评估为 true,因为您将name()中的const char*指针与明确存储在 memory 中的字符串文字进行比较,所以两个 memory 地址的评估结果不相等。 And since you are doing that comparison inside a while(1) loop, that is why "please input integer" is printed out endlessly.而且由于您是在while(1)循环内进行比较,这就是为什么"please input integer"被无休止地打印出来的原因。 You don't have any viable error handling in your loop.您的循环中没有任何可行的错误处理。

You have to look at cin 's actual state to know whether >> fails, eg:您必须查看cin的实际 state 才能知道>>是否失败,例如:

#include <iostream>
#include <string>
#include <limits>
using namespace std;

int main() {
    while (1) {
        int num;
        // cin >> num;
        // if (cin.fail()) {
        if (!(cin >> num)) {
            cout << "please input integer" << endl;
            cin.clear();
            cin.ignore(numeric_limit<streamsize>::max(), '\n');
            continue;
        }
        // use num as needed...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM