I want to be in a WHILE loop until I stop writing to a Char in C ++

0

I want to read a text infinitely until I stop writing, and count the vowels. But I stop writing and I do not leave the WHILE loop, why? Thanks for the help :) Here I leave the code:

unsigned aCnt = 0, eCnt = 0, iCnt = 0, oCnt = 0, uCnt = 0;
char ch;
std::cout << "Write something: " << std::endl;

while (std::cin >> ch) {
    switch (ch) {
    case 'a':
        ++aCnt;
        break;
    case 'e':
        ++eCnt;
        break;
    case 'i':
        ++iCnt;
        break;
    case 'o':
        ++oCnt;
        break;
    case 'u':
        ++uCnt;
        break;
    }
}
std::cout << "Number of vowel a: " << aCnt << '\n'
    << "Number of vowel e: " << eCnt << '\n'
    << "Number of vowel i: " << iCnt << '\n'
    << "Number of vowel o: " << oCnt << '\n'
    << "Number of vowel u: " << uCnt << std::endl;
    
asked by MAP 10.09.2018 в 13:39
source

2 answers

3

std::cin stays waiting to receive a value for the standard input. By having the instruction as a condition of the loop you are waiting for an input value infinitely. I suggest that if you want to stop reading, use a variable to control the loop or some input string to stop the loop, for example:

Leer = true;
while (Leer)
{
    char c; 
    std::cin >> c;

    if (c == 'Q' || c == 'q')
    {
        Leer= false;
    }
}
    
answered by 10.09.2018 / 14:06
source
2
std::cin >>

When reading from stream , if there is nothing to read the program is blocked until there is something to read or the stream is closed. The OS provides the data (from standard input, from a file, from the network ...).

There is no concept of "stop writing". Which is fortunate, because at the speed at which a computer works, you have plenty of time to notice that you have "stopped writing" no matter how fast you type.

What you can do is, for example, close the standard output (CTRL + Z in Windows console, CTRL + D in Windows) that you detect when cin.eof() returns true

Apart from that, there are ways to make programs that detect the "stop writing":

  • instead of working with STDIN, your program detects the keys pressed and, with a timer, they detect when X seconds have passed since the last key pressed. The problem is that you will have to process all the keys with your program, instead of having a stream that already gives you the text directly, and it is much more complicated.

  • you have a thread that reads from the STDIN and another thread with a watchdog . Every time you read STDIN, you reset a variable. If you spend too much time without resetting, the watchdog ends the program.

answered by 10.09.2018 в 14:12