You probably are familiar with std::cin
- that does not distinguish between enter and space for number input; that is, if your write:
int a, b;
std::cin >> a;
std::cin >> b;
Your program will expect 2 numbers, accepting both
1
2
or
1 2
What you want to do sounds like you only want to accept the second format, and decide based on the user input whether it contains one or two numbers. For that, use std::getline
:
std::string line;
std::getline(std::cin, line);
Then, you need to "tokenize" the line, i.e. split it into parts separated by spaces:
std::string::size_type pos = line.find(' ');
if (pos == std::string::npos)
{
// only 1 input
}
else
{
// more than 1 input, split, e.g. with "line.substr(...)"
}
Full code:
#include <iostream>
int main()
{
std::string line;
std::getline(std::cin, line);
std::string::size_type pos = line.find(' ');
if (pos == std::string::npos)
{
int firstnum = atoi(line.c_str());
std::cout << "One number: " << firstnum << "\n";
}
else
{
int firstnum = atoi(line.substr(0, pos).c_str());
int secondnum = atoi(line.substr(pos+1, line.size()-pos).c_str());
std::cout << "Two numbers: " << firstnum << ", " << secondnum << "\n";
}
return 0;
}
Test run with one number:
1
One number: 1
Test run with two numbers:
1 2
Two numbers: 1, 2
Here we currently ignore the possibility of the user entering more than two numbers. You could check that, again with line.find
, this time starting from pos+1 (see second parameter). The above code also does not check whether the input string starts with a space, which would result in 0 being recognized as first input... so it might be a bit trickier than using std::cin
(which automatically skips whitespace if used for numbers). Look into string tokenization for more resilient ways of splitting the input.