lundi 26 juillet 2021

Problem with cin which does not provide correct results

The following code is not mine. It's taken from Think Like a Programmer by Anton Spraul. The book pretends to use cin in a way it can get multiple inputs before the user hits Enter, with logic between them. Here's the code:

#include <iostream>
using namespace std;

main()
{
    cout << "Enter a number with as many digits as you like: ";
    char digitChar = cin.get();
    int number = (digitChar - '0');
    digitChar = cin.get();
    while(digitChar != 10){
        number = number * 10 + (digitChar = '0');
        digitChar = cin.get();
    }
    cout << "Number entered: " << number << "\n";
}

As you can see the cin.get() is used multiple times, this suggests that after the user type any digit, the code continues to run even if the user has not hit the Enter key. It doesn't make any sense to me, and it doen't work neither (for example if I enter "719" I get 1228 as a result", but my question is:

Is this code correct and the problem is due that it only work under some compileres and not under others or does it contain errors the author didn't care to check?

I noticed the same problem every time the book use cin.get() in this, apparently incorrect, way.

So to summarize: Is the code correct? Why does it produce incorrect results? If the code is correct, how does cin.get() may work this way?

Any insight will be appreciated.

Ah I almost forgot: I tried this code using GCC under Windows 10.

Aucun commentaire:

Enregistrer un commentaire