So I'm new to C++ and I'm supposed to get a vector in integers from stdin. I tried using std::cin and std::getline and other functions, but everytime I try entering a sentinel (e.g. not an integer) or when there is a "count" variable that reaches an increment, I end up in a hung state. I can enter inputs, but no more print statements (e.g. "std::cout << "added") appear after the count has reached. I'm not sure what went wrong with the std::cin.
std::vector<int> Game::getIds() {
std::vector<int> cards;
int x =0 ;
std::string mystr;
bool keepGoing = true;
int count = 0;
while (keepGoing) {
std::getline(std::cin, mystr);
std::stringstream sstream(mystr);
while (sstream >> x) {
std::cout << "added" << x << std::endl;
cards.push_back(x);
}
if (std::cin.fail()) {
keepGoing = false;
std::cout <<"fail";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return cards;
}
++count;
if (count == 5) return cards;
}
return cards;
}
cin controls input from a stream buffer, which put your input characters in a stream buffer, then it was passed to getline
.
cin
ends input when you signaled EOF
with Ctrl+D
, Ctrl+Z
, or Enter
.
See this link
detecting end of input with cin.
getline extracts characters from input and appends them to str until it meet one of the end conditions,
in your situaton the end condition is the endline character '\n'
, because the default delimeter is the endline character.
You may define your own delimeter getline(intput, str, $your_delemeter)
, and do a little experiment.