sion
sion

Reputation: 1477

Check if anything is in cin buffer

I am writing a program that requires the user to enter some input via the console. Sometimes this will be one string, sometimes it will be two. I need to be able to check if one or two strings have been entered. What I am trying at the moment is this:

string s1,s2;
cin >> s1;

// do some operations on s1 (nothing using cout/cin)

if(thereIsASecondString()) {
    //do some operations on the second string
}

I am hoping there is some sort of function that I can use to see if a second string was entered. After searching I found things like cin.eof(), cin.peek() and cin.rdbuf but I either can't use them properly or they don't suit the purpose. Can someone tell me if there is a function that can achieve what I need (check if anything was entered after the first string)?

Alternatively, I could use getline() and then loop through that and split it into two strings where the space is (if there is one). Is this a better option? I would still like to know if it is possible to do with cin.

Upvotes: 0

Views: 1025

Answers (1)

Thomas
Thomas

Reputation: 181745

Use an istringstream in combination with getline:

string line;
if (!getline(cin, line)) {
  // handle error...
}

istringstream iss(line);
string s1, s2;
if (!(iss >> s1)) {
  // we didn't even get one string, handle error...
}

// do something with s1

if (iss >> s2) {
  // there was a second string, do something with it
}

Upvotes: 1

Related Questions