문제

int n;
while(cin>>n)
    cout << n; // Run by the program if received an int value
cout << "Break from loop"; // Run by the program
cin >> n; // Skipped by the program
cout << n; // Run by the program

cant accept another input after terminating the while loop using characters.

How to accept another input if the input within the loop has been terminated using non-integer/floating-point values.

도움이 되었습니까?

해결책

If you are not terminating the program by returning end of file (i.e. Ctrl-D) or terminating the program altogether (i.e. Ctrl-C).

That is, if you exit the loop via incorrect data type, such as typing in the letter d instead of an integer, you can follow the while loop with cin.clear() and getline(cin, str), where str is some string you declare ahead of time.

You should be able to accept input for the second cin at after this.

So,

string str;
int n;
while(cin>>n)
    cout << n << endl;
cin.clear();
getline(cin, str);
cout << "Break from loop" << endl;;
cin >> n;
cout << n;

다른 팁

int n;
while(cin>>n) // Keep asking for value to input
    cout<<n<<"\n"; // This loop will never terminate for any Supplied val
//Above loop will terminate only when no more valued is supplied to code
// Hence once, we stopped entering the value, code will execute next line
// And end without asking for anymore value.
 cout<<"Break From Loop \n";

Assuming your question is "How do I resume input after the stream state has been set?" then there is a simple explanation:

The while loop in which you performed the extraction terminated only until the extraction failed; this also includes when the stream reaches the end of the input stream (EOF). When that happens the eofbit will be set in the steam state (as well as the failbit). A stream can't be used for I/O when its stream state is set. In order to use it again, the stream state must be cleared. This is done using the member function clear(std::ios_base::iostate err = std::ios_base::goodbit).

std::cin.clear();

That call will clear the bits in the stream state and assign them to 0 (std::ios_base::goodbit). After this call the stream can be used for I/O again.

This is assuming the stream read all the characters until it reached EOF. It's not sufficient for a pervious read that terminated upon the acquisition of invalid data. One would also have to ignore() the remaining characters.

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top