Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is cin apparently skipping input in this C++ code?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
   }

}

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading