Say you wanted a user to enter a base for a root, and another number for the root. But, if the user only provides 1 number, the 2nd input will default to 2, so a square root.
I want to know how to stop the input if 'enter' was pressed after entering only one number.
I am using c .
CodePudding user response:
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.
CodePudding user response:
you may try this code:
#include <iostream>
using namespace std;
int main() {
int x, y;
int sum;
cout << "Type a number: ";
cin >> x;
cout << "Type another number: ";
cin >> y;
sum = x y;
cout << "Sum is: " << sum;
return 0;
}
CodePudding user response:
I got your mean, you can use ASCII to help you.
Below is the code:
#include<iostream>
using namespace std;
int main()
{
cout << "Enter two numbers:" << endl;
int num1;
int num2 = 2;
cin >> num1;
if (cin.get() == 32)
cin >> num2;
cout << num1 << "\t" << num2 << endl;
return 0;
}
In this way, if the user enter only one number with enter, the num2 will not be changed; If the user enter one number, then space, and enter another number, the num2 will be changed as the second num2.
You could use it as a reference to complete your sqrt function.