How to stop loop using any character

i want to stop loop by entering any character like "n" in int type variable.The problem is that i cant enter character in int type variable . Any one can help me ?
Last edited on
Just let the stream extractor fail and then reset the stream:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

using std::cin;
using std::cout;

int main()
{
    int i;
    char ch;
    while (cin >> i) {
        cout << " read integer " << i << '\n';
    }
    cin.clear();
    cin >> ch;
    cout << "Read character " << ch << '\n';
}
The problem is that i cant enter character in int type variable
You can. If the stream detects a non numeric character for a numeric variable it will enter the error state. cin (or any other stream) will return false which you can use to end the loop:
1
2
3
4
5
int i;
while(cin >> i)
{
...
}

After the loop is done use clear() to clear the error state:

http://www.cplusplus.com/reference/ios/ios/clear/

Then you can read the entered [non numeric] character.
thanks chayden
Topic archived. No new replies allowed.