Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused about while check

I'm confused about this code:

#include "stdafx.h"
#include "std_lib_facilities.h"

int main()
{
    string name_one;
    string name_two;
    string name_three;    

    cout << "Please enter a name: ";
    cin >> name_one;
    cout << "\nReading data...";

    while (name_one.empty())
    {
        cout << "\nFailed!";
        cout << "Please enter a name: ";
        cin >> name_one;
        cout << "\nReading data...";
    }

    cout << "Completed!\n";

    keep_window_open();
    return 0;
}

It is very easy, but when I debug it and for example I don't write anything but just press Enter, it doesn't do anything. Just keeps showing me a flashing underscore under the line, and if I keep pressing Enter it just jumps line by line. Why does the program not read the condition? What I want is that if the user doesn't write anything, the condition in the while starts!

like image 717
RavenJe Avatar asked Feb 11 '26 16:02

RavenJe


1 Answers

You're using a stream extractor, >>, which is a formatted input function. For many types (such as fundamental types and std::string), these start by skipping all whitespace currently in the stream(1), then extracting characters as long as these are a valid representation of the data type you want to extract.

In other words, when you just press Enter on standard input, there will only be a newline character in the stream. A newline is whitespace, so the >> function is still stuck inside its "skip starting whitespace" mode. Only when you enter a non-whitespace character will the second part ("extract characters and try to interpret them as a representation of the extracted type") kick in.

If you want to always read by lines, you can use the getline stream function, or the std::getline function. You can also combine these with an istringstream object for parsing the line.


(1) This behaviour can be controlled by the stream manipulators skipws and noskipws, or directly by the stream's formatting flags.

like image 97
Angew is no longer proud of SO Avatar answered Feb 15 '26 10:02

Angew is no longer proud of SO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!