Question

Hey everyone just a quick question.

Say I have a integer variable that I will be using to store something the user will be inputing.

So like -
int x;
cin >> x;

then I want to have an option where the user can enter a string as well which I have a variable for.


how would I go about having the input detect both integers and strings or is there a better method?
The only way I am aware of by achieving this is to input straight into a string and then use some validation and functions to check whether it is an integer or not. If you input straight into an integer it would take everything up to an invalid character that can't be stored in an integer like a letter for example. But then if it was a string it would have been lost.

So the best way I know is to input into a string and do some checks on it by maybe using the std::stoi() string function or a custom written function you made yourself.
Last edited on
Just use multiple stream extraction operators (>>).

Here's a small program demonstrating this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>

using namespace std;

int main() {
	int x;
	string y;

	cout << "Enter integer and string: ";
	cin >> x >> y;
	cout << "y: " << y << " x: " << x << endl;

	return 0;
}


It will read the first integer and the first string and store them in x and y respectively.
pnoid but what I'm trying to accomplish is for the program itself to detect whether the data that's being inputted is an integer or a string. I want the user to only have to input one thing.

Topic archived. No new replies allowed.