Checking Value

Hi there,

I was wondering if someone one here could help me please. I want my program to only allow numbers to be entered and if there is any other character then it should display an error message. I can't seem to get it to work so if someone could help me i would really appreciate it.

I am pretty new to programming so please go easy XD

Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <string>

using namespace std;

void validate(string number, bool valid)
{
	int value = 0;

	do
	{
	      if(number.length() == 5)
	         {
	              int newNumber = atoi(number.c_str());
		      valid = 1;
		      cout<<newNumber;
		      cout<<endl;
		 }
					
	     if(number.length() != 5)
		{
		     cout<<"You must enter input a 5 digit number: ";
		     cin>>number;
		     cout<<endl;
		     valid = 0;
		}
				
	}
	while(valid != true);
}
void main()
{
	string number;
	bool valid = 0;

	cout<<"Please input a 5 digit number: ";
	cin>>number;
	cout<<endl;

	validate(number, valid);

	system("PAUSE");
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>

bool validate(const std::string& number)
{
    //http://en.cppreference.com/w/cpp/algorithm/all_any_none_of
    //http://en.cppreference.com/w/cpp/string/byte/isdigit
    return number.size() == 5 && std::all_of(number.begin(), number.end(), ::isdigit);
}


int main() //Main returns int, void main() is invalid C++
{
    std::string number;
    do { //Take correct input first
        std::cout << "Please input a 5 digit number: ";
        std::cin >> number;
    } while( !validate(number) );

    //Then convert it to number and output it
    //http://en.cppreference.com/w/cpp/string/basic_string/stol
    std::cout << std::stoi(number) << '\n';
}
Topic archived. No new replies allowed.