Problems using cin.ignore ();

1

What I want to do with cin.ignore(256,'\n'); is to clean the keyboard buffer, so that in the 2nd loop while can enter the data.

But the monento execute it I realize I have not achieved my goal, and because of my inexperience I do not know what error I've been committing.

Here is the code of what I have achieved:

#include<iostream>
using namespace std;


int main() {
   int a = 0, b = 0, n,i;
   while (cin >> n) {// ingreso " 1 2 3 " y un caracter para cerrar el bucle
      a += n;
   }
   cin.ignore(256,'\n');
   while (cin >> i) {// ingreso " 4 5 6 " y un caracter para cerrar el bucle
      b += n;
   }
   cout << a <<' '<< b << endl;
}

If everything had gone as planned, the output would be: 6 15

BUT the output I get is: 6 0 .

    
asked by bassily 20.08.2016 в 00:40
source

1 answer

1

The program has 2 errors:

First error

It is still necessary to use cin.clear() , which is responsible for cleaning the flags ( error state flags ), by not doing this the second cin did not work because the values of the flags indicated that had presented a eofbit (indicating the end of the stream).

Second error

Within the second while, we have b += n , but the variable that is being read is i , therefore this should be b += i .

Finally the program should be:

#include<iostream>
using namespace std;


int main() {
   int a = 0, b = 0, n,i;
   while (cin >> n) {// ingreso " 1 2 3 " y un caracter para cerrar el bucle
      a += n;
   }

   cin.clear();  // 1er error, provoca que no entre al siguiente ciclo

   cin.ignore(256,'\n');

   while (cin >> i) {// ingreso " 4 5 6 " y un caracter para cerrar el bucle
      b += i;   // 2do error, suma la variable incorrecta
   }

   cout << a <<' '<< b << endl;
}

The output you get is:

$ ./cin_ignore 
1 2 3 \n
4 5 6 \n
6 15
    
answered by 10.11.2016 / 20:46
source