c++ - Char数据类型输入问题

标签 c++ if-statement inputstream do-while

有谁知道为什么当我在“cInputCommandPrompt”中输入多个字符时,它会循环“按”“Y”继续,而不是像我想要的那样只显示一次,所以我尝试清除缓冲区?如果那是您所说的,但是它似乎没有用。如果有人可以帮助我,我将不胜感激。我基本上是想要它的,所以当用户不输入“Y”时,它会重新循环直到他们输入正确的字符为止,只是不喜欢我尝试排序的多个字符输入。

void ContinueOptions()
{
    bool bValid = false;
    char cInputCommandPrompt = 0;
    do{
        std::cout << "Press ""y"" to continue: ";
        std::cin >> cInputCommandPrompt;
        cInputCommandPrompt = std::toupper(static_cast<unsigned char>(cInputCommandPrompt));

        if (!std::cin >> cInputCommandPrompt)
        {

            std::cin.clear();
            std::cin.ignore(100);
            std::cout << "Please try again.";
        }
        else if (cInputCommandPrompt == 'Y')
        {
            bValid = true;
        }
    }while(bValid == false);
    std::cout << "\n";
}

最佳答案

if语句中存在无效条件

    if (!std::cin >> cInputCommandPrompt)

应该有
    if (!( std::cin >> cInputCommandPrompt ) )

至少重写功能,例如,如下面的演示程序中所示。
#include <iostream>
#include <cctype>

void ContinueOptions()
{
    bool bValid = false;
    char cInputCommandPrompt = 0;
    do{
        std::cout << "Press ""y"" to continue: ";

        bValid = bool( std::cin >> cInputCommandPrompt );

        if ( bValid )
        {
            cInputCommandPrompt = std::toupper(static_cast<unsigned char>(cInputCommandPrompt));
            bValid = cInputCommandPrompt == 'Y';
        }

        if ( not bValid )
        {

            std::cin.clear();
            std::cin.ignore(100, '\n');
            std::cout << "Please try again.\n";
        }
    } while( not bValid );
    std::cout << "\n";
}

int main(void) 
{
    ContinueOptions();

    std::cout << "Exiting...\n";

    return 0;
}

关于c++ - Char数据类型输入问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59896428/

相关文章:

c++ - Visual C++ 2010 : deterministic build? 如何区分 exe/dll 文件?

java - 在InputStream和FileInputStream之间切换的简单方法?

c++ - SFML 库 : strange error

c - 程序没有输出完整的字符串

xcode - 有没有更好的方法来处理 Swift 的嵌套 "if let" "pyramid of doom?"

if-statement - Enterprise Architect 文档模板条件,例如 `if` 和“else”

java - 通过InputStream对象读取文件

Java - 如何使用输出流向子进程发送值?

c++ - 为什么编译器似乎忽略了模板类中的 if 语句?

c++ - 如何用不同 namespace 中的候选人消除 ADL 调用的歧义?