0

I have a function in which I want to read integers until I enter a non integer. And I want to repeat that function until I press enter. But the character gets passed to the second cin and it becomes an infinite loop.

void  read () {
    int  x;
    while ( cin >> x );
}

int main () {
    char  a;
    do {
        read ();
        cin.ignore (256, '\n')
        cin >> a;
    } while ( a != '\n' )
}
  • The issue here is that the cins appear to be connected somehow even though the variables are in different functions. –  Apr 08 '16 at 09:59
  • 3
    There **is** a single global variable [`cin`](http://en.cppreference.com/w/cpp/io/cin). – axiac Apr 08 '16 at 10:23
  • Ok but I have to get rid of the `'\n'` at the end ot the first `cin` so I can read anything with the second. And the `cin.ignore()` isn't doing anything. –  Apr 08 '16 at 10:32

1 Answers1

2

1) you forgot to remove the fail bit in std::cin; use clear()

2) to detect an empty enter, I suggest to use a std::string and std::getline()

I suggest something like

#include <iostream>
#include <string>

void  read () {
    int  x;
    while ( std::cin >> x ) ;
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<int>::max(), '\n');
}

int main () {
    std::string  b;

    do {
        read();
        std::getline(std::cin, b);
    } while ( false == b.empty() );

    return 0;
}
R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
max66
  • 65,235
  • 10
  • 71
  • 111