0

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; 
}
user6461080
  • 129
  • 7
  • Why don't you just use `while (std::cin >> x)`? – fas Jun 30 '20 at 04:03
  • I tried that too but I run into the same issue where if I provide a sentinel or "CTRL+D" or a character, my terminal stops working. I can keep carriage returning and providing new input but I can't break out (even if I use "breaks"). – user6461080 Jun 30 '20 at 04:24
  • What output do you exactly expecting from your hypothesis? – Rohan Bari Jun 30 '20 at 04:43
  • So I'm trying to get a series of integers from stdin and put them into a vector. Of course, I would need to do some defensive programming against bad inputs and the like, but I can't even get to that when my cin just hangs. After entering 5 integers and carriage returning them, I expected that the "count" variable will reach 5 and break out of the while loop and function for me. I tried breaking out of this "while" loop in so many ways, but none of them seem to work. – user6461080 Jun 30 '20 at 04:53

1 Answers1

1

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.

Yong Yang
  • 126
  • 6