Detecting char when int is desired from cin

While I'm in school and studying C++ this is not a question that is part of a homework assignment, just an oddity I came across and I'm wondering how to solve for myself and future reference.

Searching I didn't see anything that seemed to relate to this directly.

So I'm looking for input of type int, but I noticed when running a program that if a char input is received (not sure about string) that it is converted to int (I read in my textbook that this is normal C++ behavior).

My question is : how do I test for type char on input since it is automatically converted to int? I'm used to Python, Ruby, PHP, etc where there are usually some standard library methods for this, but in searching here and google there doesn't seem to be. Below is a stripped down version of what I was using when I discovered this problem.

I'm also wondering: What does C++ get the value for the char from? Is it the ASCII value or something else? If you run the code below and type in any single alphabet character you'll see what I'm talking about.

Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<iostream>
using namespace std;

int main()
{
	int user_input;
	int n;
	
	cout << "Enter a number: ";
	cin >> user_input;
	
	for (n = 0; n < user_input; n++)
	{
		cout << n << endl;
	}
	
	cout << user_input << endl;
	
	return 0;
}
Topic archived. No new replies allowed.