简体   繁体   中英

C++: in while(cin) loop, sometimes the loop is ignored

In my code, I tried to create a loop, but every once in a while the whole loop is ignored after it gets my input.

This is the loop:

while(std::cin >> word){
        std::cin.clear();

        qType = (rand()%2) + 1;
        letter = (rand()%26) + 1;
        if(qType == 1){
            std::cout << letter << std::endl;
        }else if(qType == 2){
            std::cout << Letters[letter] << std::endl;
        }
}

When I write my input, the first few times the loop successfully outputs either a letter, or its corresponding number, but shortly after, it stops doing so. I found people with similar problems, but for them the solution was to add a cin.clear(); function, which I added to the end first, and then the start, but it didn't fix the problem.

First of all, what should be the end of you while loop? The way you have your loop set up, it will never end. Also you aren't using word variable nowhere inside your loop so what is the point of it. If you want to loop until the user inputs some exit code it should look like this:

std::string word;
while (word != "exit") {
    std::cin >> word;
    // your code
}

try this

while(std::cin >> word && word != '\n'){
    std::cin.clear();

    qType = (rand()%2) + 1;
    letter = (rand()%26) + 1;
    if(qType == 1){
        std::cout << letter << std::endl;
    }else if(qType == 2){
        std::cout << Letters[letter] << std::endl;
    }

}

first of all, you didn't give a termination condition so maybe this code work for you...

while(word!="exit"){
    cin >> word;

    qType = (rand()%2) + 1;
    letter = (rand()%26) + 1;
    if(qType == 1){
        cout << letter << std::endl;
    }else if(qType == 2){
        cout << Letters[letter] << std::endl;
    }
            cin.clear();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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