collin sim collin sim - 9 months ago 38
C++ Question

i have to cin my name to enter my resources how do i do that

cin << name << endl;
cout >> "my name is " << name << endl;

Answer Source


When you say cin >> smth, you want to get precisely smth, nothing more. End-line marker is not part of it, so it's not consumed. Unless you would have a special type for line, but there is no such thing in standard library.

When you use getline you say you want to get a line. A line is string that ends with \n, the ending is integral part of it.

So the problem is that std::cin leaves an end-line \n character in buffer.


std::cin >> smth;

|'H'|'e'|'l'|'l'|'o'|'\n'|      // In smth will be "Hello"

|'\n'|                          // But new-line character stays in buffer

std::cin >> smth2;              // Its same like you would press just an 'enter', so smth2 is empty


  • Use std::cin.getline


  • Use std::cin >> smth; + std::cin.ignore();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download