C++ User input verificartion

Hello C++ programmers,

I am finding it difficult to write a programme in C++ that automatically knows whether you have inputted 1 or more numbers. I want the user to input 1 number and not two and when I do enter 2 or more number I want it to say "Too many numbers try again".please help if you know how to do this, Thanks.

//myexample
#include <iostream>
#include <string>

int main()
{
int number;


std::cout<<"enter 1 num: "<<std::endl;
std::cin>>number;
if(number == number && number){
std::cout<<"Too long";
return 1;
}
else if (number == number){
std::cout<<"Your number is "<<number<<std::endl;
}

return 0;

}
What counts as two numbers?

Which of the following inputs count as two numbers?

1
12
1 2
By 1 number i mean just 1 number for e.g 12, but i dont want the user to input 12 and 13 seperatly, i want the programme to automaticaly recognise that the user has inputed 2 numbers seperatley (12 13) and print out a statement saying that u cant input two seperate numbers.
Last edited on
The last input u did would count as two seperate numbers
cin >> number; will automatically take the numbers one at a time.

If you want to get the whole input and check it for spaces, you'll have to take in the entire input as a string including spaces, then look for the spaces yourself.

To fetch the entire string, including spaces:

1
2
string input;
std::getline(std::cin, input);
Last edited on
Cin>>number; will take only 1 number at a time but i want it as if the user inputed 2 seperate numbers, the programme to realize that it's more than 1 number and to point to the user that the programme only takes 1 number at a time
What ur saying is true which is if i input 2 numbers seperatley thw programme will take the first number and avoid the second number. what i want is the programme to realize when the users inputed 2 or more seperate numbers and automaticaly show that that's too much numbers.

Repeater

Could you display what u said about using strings and spaces on a programme to test it, it would really help. Thanks for the feedback👍
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>

int main()
{
	std::string input;
	std::getline(std::cin, input);

	if (input.find(' ') != std::string::npos)
	{
		std::cout << "You input something with a space in it. Don't do that.";
	}
	else
	{
		std::cout << "You input something without a space in it.";
	}
}
Thanks for that, really helpful👍
Topic archived. No new replies allowed.