简体   繁体   English

用户输入的整数后跟垃圾

[英]User input of integer followed by garbage

In my simple Fraction class, I have the following method to get user input for the numerator , which works fine for checking garbage input like garbage , but will not recognize user input which starts with an integer, and is followed by garbage, 1 garbage or 1garbage . 在我简单的Fraction类中,我具有以下方法来获取numerator用户输入,该方法可以很好地用于检查诸如garbage类的garbage输入,但无法识别以整数开头,后跟垃圾, 1 garbage1garbage

void Fraction::inputNumerator()
{
    int inputNumerator;

    // loop forever until the code hits a BREAK
    while (true) {
        std::cout << "Enter the numerator: ";

        // attempt to get the int value from standard input
        std::cin >> inputNumerator;

        // check to see if the input stream read the input as a number
        if (std::cin.good()) {

            numerator = inputNumerator;
            break;

        } else {

            // the input couldn't successfully be turned into a number, so the
            // characters that were in the buffer that couldn't convert are
            // still sitting there unprocessed.  We can read them as a string
            // and look for the "quit"

            // clear the error status of the standard input so we can read
            std::cin.clear();

            std::string str;
            std::cin >> str;

            // Break out of the loop if we see the string 'quit'
            if (str == "quit") {
                std::cout << "Goodbye!" << std::endl;
                exit(EXIT_SUCCESS);
            }

            // some other non-number string.  give error followed by newline
            std::cout << "Invalid input (type 'quit' to exit)" << std::endl;
        }
    }
}

I saw a few posts on using the getline method for this, but they didn't compile when I tried them, and I'm having trouble finding the original post, sorry. 我看到了一些关于使用getline方法的帖子,但是当我尝试使用它们时它们并没有编译,抱歉,我在查找原始帖子时遇到了麻烦。

Better check as follows: 更好的检查如下:

// attempt to get the int value from standard input
if(std::cin >> inputNumerator)
{
    numerator = inputNumerator;
    break;
} else { // ...

Or yes: Follow recommendations to parse a complete input line combining std::getline() and std::istringstream appropriately. 或是:按照建议来解析完整的输入行,以适当地组合std::getline()std::istringstream

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

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