The easiest way is probably to use istringstream
.
I'm not sure what you consider valid input so the only error checking I've used is that the istringstream
is in a good state.
I've modified inputString()
to take the full input string
, which you would get from cin
.
#include <iostream>
#include <sstream> // for std::istringstream
using namespace std;
// Note call by reference for the three last parameters
// so you get the modified values
int inputString(string input, string &name, string &keyWord, bool &trueFalse){
std::istringstream iss(input); // put input into stringstream
// String for third token (the bool)
string boolString;
iss >> name; // first token
// Check for error (iss evaluates to false)
if (!iss) return -1;
iss >> keyWord; // second token
// Check for error (iss evaluates to false)
if (!iss) return -1;
iss >> boolString; // third token
// Check for error (iss evaluates to false)
if (!iss) return -1;
if (boolString == "!") trueFalse = false;
else trueFalse = true;
return 0;
}
int main() {
string input, name, keyWord;
bool trueFalse;
//cin << input;
// For this example I'll just input the string
// directly into the source
input = "ducks hollow23 !";
int result = inputString(input, name, keyWord, trueFalse);
// Print results
cout << "name = " << name << endl;
cout << "keyWord = " << keyWord << endl;
// Use std::boolalpha to print "true" or "false"
// instead of "0" or "1"
cout << "bool result = " << boolalpha << trueFalse << endl;
return result;
}
The output is
name = ducks
keyWord = hollow23
bool result = false