DangerMoose
DangerMoose

Reputation: 105

Cin until end of input

I need to read in a string and then an integer until the user indicates end of input (ctrl-d in linux). Again, I am stuck. Currently I have a while loop:

while (getline(cin, line))

However, that gives an entire line and then I cannot seem to separate the string from the integer. Suggestions would be most appreciated! :)

Upvotes: 3

Views: 5533

Answers (2)

timetocodebutlazyyy
timetocodebutlazyyy

Reputation: 11

cin>>a

The above statement reads a token from standard input and stores it in the a variable. What is less known is that it also returns a bool value. When you reach the end of all standard input, the above statement would return false. Use it in an if statement!

if(c>>a){
  cout<<"End of standard input has been reached!";
}

Upvotes: 1

manasij7479
manasij7479

Reputation: 1695

If the string and the integer is separated by whitespace; Do this:

while(std::cin>>your_string>>your_num>>std::ws){}

You can choose your own delimiter, by writing a manipulator yourself.

Another approach would be to do it your way, and put the input line into a stringstream and extract the string and numbers from it. That approach seems roundabout to me as you get strings from a stream only to put it into another stream.

Upvotes: 5

Related Questions