Originally Posted by
Erik Ingvoldsen
The test, however, asks me to input two things for some reason.
Because now you call getline twice, discarding the input from the first call:
Code:
std::getline(std::cin, line);
if (getline(std::cin, line)) {
Originally Posted by
Erik Ingvoldsen
I admit, I should have asked you from the start what these if statements were doing exactly but I was stressing over other problems with the code. But it's better that I understand what's going on, so I'd also like to ask what's happening here.
Code:
if (getline(std::cin, line))
{
std::stringstream ss(line);
if (ss >> result && ss.eof())
{
First, getline is called to read a line from standard input. (I did not qualify getline here because of argument dependent lookup: since cin is in the std namespace, the compiler will search for a matching function named getline in the std namespace.) Then, the return value of getline is checked to ensure that it was successful. Next, since a line was successfully read, a string stream (i.e., input/output streams, but string based) is created from that line. We then extract/parse the line via the stringstream into result. The return value of that operation is checked, and finally we check that the end of file condition has been set on the string stream, i.e., to detect unwanted input like a stray alphabetic character after the integer input.