Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read cin with whitespace up until a newline character?

Tags:

c++

string

cin

I wish to read from cin in C++ from the current position up until a newline character into a string. The characters to be read may include spaces. My first pass fails because it stops on the first space:

string result;

cin >> result;

If cin is given:

(cd /my/dir; doSometing)\n

The variable result only gets:

(cd

I would think I should be able to use stream manipulators to accomplish this, but the skipws was not quite right in that it throws carriage returns in with spaces and tabs, plus it sounds like that is for leading whitespace to be skipped.

Perhaps I need to use streambuf something like this?

streambuf buf;

cin >> buf;
like image 789
WilliamKF Avatar asked Oct 18 '09 01:10

WilliamKF


People also ask

How do you get Cin to read whitespace?

Using cin. You can use cin but the cin object will skip any leading white space (spaces, tabs, line breaks), then start reading when it comes to the first non-whitespace character and then stop reading when it comes to the next white space. In other words, it only reads in one word at a time.

Does CIN get read newline?

getline(cin, newString); begins immediately reading and collecting characters into newString and continues until a newline character is encountered. The newline character is read but not stored in newString.

Does CIN stop at newline?

cin is whitespace delimited, so any whitespace (including \n ) will be discarded. Thus, c will never be \n .


1 Answers

std::string str; 
std::getline( std::cin, str);
like image 58
KeatsPeeks Avatar answered Sep 20 '22 01:09

KeatsPeeks