【问题标题】:Inputting char and int in int variable using cin in C++ [duplicate]在C ++中使用cin在int变量中输入char和int [重复]
【发布时间】:2021-04-11 06:19:14
【问题描述】:

我正在编写一个代码来从用户那里获取一个整数 ID,该 ID 稍后会从一个文件中进行验证。 现在,当我没有在 cin 中输入有效输入时,它不起作用(显然)。我在下面附上了一个示例代码:

std::cout << "Enter ID : " << std::endl;
std::cin >> id;

就这么简单。 现在,如果我输入像 a 或任何其他字符这样的输入,我可以使用 cin.fail() 检查任何错误 但是,如果我输入像 11a 这样的输入,这似乎不起作用。我在互联网上搜索了很多,但找不到任何合适的解决方案。

【问题讨论】:

    标签: c++ validation char integer cin


    【解决方案1】:

    首先欢迎来到 Stack。试试这个

    #include <iostream>
    #include <string>
    
    int main() {
    
        std::string theInput;
        int inputAsInt;
    
        std::getline(std::cin, theInput);
    
        while(std::cin.fail() || std::cin.eof() || theInput.find_first_not_of("0123456789") != std::string::npos) {
    
            std::cout << "Error" << std::endl;
    
            if( theInput.find_first_not_of("0123456789") == std::string::npos) {
                std::cin.clear();
                std::cin.ignore(256,'\n');
            }
    
            std::getline(std::cin, theInput);
        }
    
        std::string::size_type st;
        inputAsInt = std::stoi(theInput,&st);
        std::cout << inputAsInt << std::endl;
        return 0;
    }
    

    我做了一个输出来可视化它。变量“inputAsInt”将是您必须进一步使用的变量。

    【讨论】:

    • 这是正确的答案(首先读取为字符串,然后验证,然后转换),但当然有效整数的定义可能会有所不同(例如负数);
    • 他说他想读取身份证,所以我认为身份证是肯定的。
    • 当然,只是为以后的读者指出。我确实对答案投了赞成票。
    • @secdet 谢谢伙计,它对我很有用。感谢您的帮助。
    • @SumranMS 没问题,欢迎您!顺便说一句:欢迎来到论坛!
    猜你喜欢
    • 2018-12-02
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    • 2013-09-02
    • 2013-03-29
    • 1970-01-01
    • 1970-01-01
    • 2013-11-09
    相关资源
    最近更新 更多