C 循环回收整数直到给出q

C++ Loop recieves integers until given Q

本文关键字:整数 循环      更新时间:2023-10-16

循环应接收输入,直到给出q或q。尽管循环期望一个整数,char q或q会破坏循环,但未被识别。我如何允许循环识别Q或Q打破循环?

int ReadInput;      // Remembers input elements given
string ReadInputString = to_string(ReadInput); // String version of the ReadInput 
        do
        {
            bool NoErrors = true;   // Make sure there were no errors while reading input
            std::cout << "Enter the next element (Enter 'q' to stop): "; // Prompt user for input
            cin >> ReadInput;
            if (ReadInputString == quit || ReadInputString == Quit) // Enter Q or q to quit
            {
                break;
            }
            /* Validation */
            if (cin.fail()) 
            {
                /* Pass by the bad input */
                NoErrors = false; // Note there was a problem
                cin.clear(); // Clear the bad input
                cin.ignore(); // Ignore the bad input
                std::cout << "Invalid number" << endl; // Error message
            }
            /* Add the input to the list (if there were no problems) */
            if (NoErrors)
            {
                NumbersList.push_back(ReadInput); // Put the given number onto the end of the list
            }
        } while (ReadInput >= 0);

最终存储数字的位置无关紧要。您正在使用Integer变量输入,并希望将炭存储在那里。因此,只需在那里带一个字符,检查它是否包含一个数字,如果是,请将其转换为num并继续,如果是char检查是Q或Q

int ReadInput;
char temp;
string ReadInputString = to_string(ReadInput); // String version of the ReadInput 
        do
        {
            bool NoErrors = true;   // Make sure there were no errors while reading input
            std::cout << "Enter the next element (Enter 'q' to stop): "; // Prompt user for input
            cin >> temp;                        //store input as char 
            if (isdigit(temp))                  //check input is number or not
                ReadInput = temp;               //convert input to num if true
            else if (temp == 'q' | temp == 'Q') //if not number check for q or Q
                break;                          //break if q
            if (ReadInputString == quit || ReadInputString == Quit) // Enter Q or q to quit
            {
                break;
            }
            /* Validation */
            if (cin.fail()) 
            {
                /* Pass by the bad input */
                NoErrors = false; // Note there was a problem
                cin.clear(); // Clear the bad input
                cin.ignore(); // Ignore the bad input
                std::cout << "Invalid number" << endl; // Error message
            }
            /* Add the input to the list (if there were no problems) */
            if (NoErrors)
            {
                NumbersList.push_back(ReadInput); // Put the given number onto the end of the list
            }
        } while (ReadInput >= 0);