Home > OS >  Why is cin apparently skipping input in this C code?
Why is cin apparently skipping input in this C code?

Time:10-12

I have a simple C test code. The way it should work is for a user to enter a sequence of integers through cin, followed by some character to terminate the cin input, then the code should output the integers. Next, the user should enter an integer other than zero to input another sequence. If that's what the user does, the process begins again, otherwise the code exits.

For example, I am expecting input

1 2 3 4 5 a

to result in output

1, 2, 3, 4, 5

followed by an opportunity to input the signal for another sequence. What happens instead is that this output gets repeated ad infinitum (or until ctrl-c):

1, 2, 3, 4, 5
1, 2, 3, 4, 5
1, 2, 3, 4, 5
etc.

What is going on with cin? I know about getline(), and could probably solve the problem with it. But, regardless, I think there is something simple and fundamental that I need to understand about cin. Here's the code:

#include <iostream>
#include <vector>


int main(int argc, char **argv) {

   std::vector<int> data;

   int goahead = 1;
   int nextval;

   while (goahead) {

      while (std::cin >> nextval) {
         data.push_back(nextval);
      }

      for (int i=0; i<data.size(); i  ) {
         if (i>0) std::cout <<", ";
         std::cout << data[i];
      }
      std::cout << std::endl;

      std::cin >> goahead;
   }

}

CodePudding user response:

Using cin.clear() and cin.ignore() can help:

#include <iostream>
#include <vector>
#include <limits>

int main(int argc, char **argv) {

   std::vector<int> data;

   int goahead = 1;
   int nextval;

   while (goahead) {

      data.clear();
      
      while (std::cin >> nextval) {
         data.push_back(nextval);
      }

      std::cin.clear();
      std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

      for (int i=0; i<data.size(); i  ) {
         if (i>0) std::cout <<", ";
         std::cout << data[i];
      }
      std::cout << std::endl;
      
      std::cin >> goahead;

      std::cin.clear();
      std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

   }
}

Best regards.

  • Related