How can I accept both int and char input?

I have a program where the user utilizes both char and int input at anytime. Is there a way to let the user input either of these, then act appropriately depending if they enter a char or an int? Thanks!
You could capture all of the input using character/strings.
If the user entered numbers (we can test for this), then we can take those numbers and cast them into an integer(or double or whatever). There are many functions available for this, like std::stoi in the string library - stoi means "string to integer."

There are, of course, many ways to do this - I am just stating how I would do it.
Last edited on
That's what I thought, but this is the only way I can think of ( with my experience ) to accomplish it.
1
2
3
4
5
6
7
8
9
10
11
12
string input;
int numberInput;
char charInput;
cin >> input;
if ( input.isdigit() )
{
   numberInput = input;
}
else
{
  charInput = input;
}

How do you use std::stoi?

closed account (SECMoG1T)
You could also use stringstream, istringstream objects.
Example please? I'm a visual learner!
1
2
3
4
int number;
std::string myString = "12345";
number = std::stoi(myString);
//do something down here 


In this case, number would have the value of "12345" (as an integer);

You could have the issue of your user entering numbers and letters in one line, so you might want to check for that. For that, you can use std::find_first_not_of to find out if any letters (or numbers) were entered that weren't supposed to be.
I don't know if you need to check for those kinds of errors. Just a thought.

Either way, the above implementation of std::stoi should do the trick.
Fantastic! Also, the function I am working on will be returning this int or char, I know there is a way to make it so the function can return either, but I'm unaware of how to do it.
Without templating, I'm unsure of any way to return an arbitrary type.
You can return a string (or array of characters) and then cast it to an integer after you called the function if necessary.

If you want to return any arbitrary type (like int or char), then you should look into templates, like shadowCODE said.

All the programs I write are written using templates, but it can take a while to get it down.
Templates are extremely useful, and can really expand the usefulness of your program. I'd really recommend learning templates.
Topic archived. No new replies allowed.