Check only 1 character input

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <string>

using namespace std;

int main(){

	char thechar;
	string ErrorMsg;
	bool isFalse = 0;

	cout << "Enter char : ";
	do{
		try{
			cin >> thechar;
			if( !cin ){
				isFalse = true;
				ErrorMsg = "Invalid input ! Only 1 letter ! ";
				throw ErrorMsg;
			}
			isFalse = false;
		}
		catch( string msg ){
			cout << msg << endl;
			cin.clear();
			cin.ignore(100,'\n');
		}
	}while(isFalse);

	system( "pause" );
	return 0;
}


but my program cannot work for only 1 letter can be input.
any idea with it?
The >> operator reads a line up to any kind of whitespace. If you want to get a single character I believe you use cin.get() http://www.cplusplus.com/reference/iostream/istream/get/

Or you can simply read the input to a c-style string (array of chars) or a string object and only check the first character.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <string>

using namespace std;

int main(){

	char thechar[1];
	thechar[1] = '\0';
	string ErrorMsg;
	bool isFalse = 0;
	char *ptr = thechar;

	
	do{
		cout << "Enter char : ";
		try{
			cin >> thechar;
			if( thechar[1] != '\0' ){
				isFalse = true;
				ErrorMsg = "Invalid input ! Only 1 letter ! ";
				throw ErrorMsg;
			}
			isFalse = false;
		}
		catch( string msg ){
			cout << msg << endl;
			cin.clear();
			cin.ignore(100,'\n');
		}
	}while(isFalse);

	system( "pause" );
	return 0;
}


here is my current code.
but i get the
error for stack around the variable for "thechar" was corrupted
Last edited on
Not sure why you get that, it compiled and worked fine for me (after I included <cstdlib> though, guessing you use visual c++ 2010?) What was the full error message?

Also, you don't need to make thechar an array, a simple char variable would have worked there. :)

And are do you want it to keep running and asking to put in more characters? Is there more code you are going to be writing into this program for other purposes later on? If not, what do you have a char pointer declared?
Last edited on
i just try with some simple code . err .
yeah. im using visual c++ 2010

this the error with pop up message
Run-Time Check Failure #2 - Stack around the variable 'thechar' was corrupted.
Topic archived. No new replies allowed.