Need help trying to only accept integers

So I coded this trying to only allow integers to be inputted. If characters are inputted it still works. Really confused on how to decline the characters and only accept integers(whole numbers). Also trying to decline the user if character was inputted to see a message like "Please input a number".
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include <iostream>
#include <fstream> //For file access
#include <string>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <stdlib.h> // string

using namespace std;
// Four Void function //

bool validate(string str1); // this will help to return true or false
void reverse(string str1);
void even(string str1);
void odd(string str1);

ofstream myfile;


int main()
{

	char again;
	string input_string;
	myfile.open("DataFile.txt");
	do
	{
		do {
			// Integer number from user //
			cout << " Please Enter a Positive integer greater than 0:\n";
			cin >> input_string;
			cout << endl;
		} while (validate(input_string)); // ask again

		cout << " the original number is: " << input_string << endl;
		myfile << " the original number is: " << input_string << endl;
		// Reverse function, even or odd //

		reverse(input_string);
		odd(input_string);
		even(input_string);

		// This seperates the next part

		cout << " --------------------" << endl;
		myfile << " --------------------" << endl;

		// this uses to ask user to repeat again
		cout << " Do you want to do it again? <y/n> " << endl;
		cin >> again;
	} while (again == 'Y' || again == 'y');
	myfile.close();
	return 0;
}
// Checking user input
bool validate(string str1)
{

	int num = atoi(str1.c_str());
	if (num < 0) // Validating user input is positive

	{
		return true;
	}
	return false;
}

// Output digits to screen and txt file
void reverse(string str1)
{
	cout << " the number reversed ";
	myfile << " the number reversed ";
	// Reverse order with a space 
	// Using the loop
	for (int x = str1.length() - 1; x >= 0; x--)
	{
		cout << str1[x] << " "; //the space
		myfile << str1[x] << " "; // the space
	}
	cout << endl;
	myfile << endl;
}

// Even function
void even(string str1)
{
	cout << " the even digits are ";
	myfile << " the even digits are ";
	for (int x = 0; x< str1.length(); x++) //same with last function so
	{
		if ((str1[x] - '0') % 2 == 0) // i just do copy and paste
		{
			cout << str1[x] << " ";
			myfile << str1[x] << " ";
		}
	}
	cout << endl;
	myfile << endl;
}


// odd function
void odd(string str1)
{
	cout << " the odd digits are ";
	myfile << " the odd digits are ";
	// same with last function {copy and paste}
	for (int x = 0; x < str1.length(); x++)
	{
		if ((str1[x] - '0') % 2 != 0)
		{
			cout << str1[x] << " ";
			myfile << str1[x] << " ";
		}
	}
	cout << endl;
	myfile << endl;
}
Hi,

Always read the documentation for the functions you use :+)

https://en.cppreference.com/w/cpp/string/byte/atoi

Looking at this documentation, 0 is returned if conversion fails. Note that it can be used with chars in the input to still produce a valid integer.

Is this backwards ?

56
57
58
59
60
61
62
63
64
65
66
bool validate(string str1)
{

	int num = atoi(str1.c_str());
	if (num < 0) // Validating user input is positive

	{
		return true;
	}
	return false;
}


There is a ternary operator:

https://en.cppreference.com/w/cpp/language/operator_other#Conditional_operator

return num > 0 ? true : false

Good Luck !!
Last edited on
Hey figured it out thanks! Also I am now trying to figure out how to make it show if there are no even or odd number to show the display as.
"There are no even digits" and "There are no odd digits".
I am using else, but it won't work.
What am I doing wrong here?

For Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Even function
	void even(string str1)
	{
		cout << " the even digits are ";
		myfile << " the even digits are ";
		for (int x = 0; x< str1.length(); x++) //same with last function so
		{
			if ((str1[x] - '0') % 2 == 0)
			{
				cout << str1[x] << " ";
				myfile << str1[x] << " ";
				{
			else ((str1[x] - '0' % 2 != 0))
				cout << "there is no even number";
				}
			}
		}
		cout << endl;
		myfile << endl;
	}
Last edited on
If you look at a number on paper, what is your brain doing (maybe unconsciously )when you want to know how many digits there are?
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>

// skip over the leading + sign, if it is present, and then skip leading zeroes
// ie. if the input is +000000123405670089000, return 123405670089000
std::string trim( const std::string& digits )
{
    std::size_t pos = 0 ;
    if( digits.front() == '+' ) ++pos ;
    while( pos < digits.size() && digits[pos] == '0' ) ++pos ;
    return digits.substr(pos) ; // throw away the leading + sign, zeroes
}

std::string get_uint_str()
{
    std::cout << "please enter a positive integer: " ;

    std::string digits ;
    std::cin >> digits ;

    digits = trim(digits) ;

    // if there is no digit left after trimming, it is an error
    if( digits.empty() ) std::cout << "please enter a number greater than zero.\n" ;

    else
    {
        // if every character left is a decimal digit, we have a valid input
        // all_of: http://www.cplusplus.com/reference/algorithm/all_of/
        // lambda expession: http://www.stroustrup.com/C++11FAQ.html#lambda
        if( std::all_of( digits.begin(), digits.end(), []( char c ) { return std::isdigit(c) ; } ) )
            return digits ; // so return it

        else std::cout << "error: input is not a number. please retry.\n" ;
    }

    return get_uint_str() ; // try again
}

std::string reverse_digits( std::string number )
{
    // first, discard trailing zeroes
    while( !number.empty() && number.back() == '0' ) number.pop_back() ;

    // return the reverse of what is left
    return { number.rbegin(), number.rend() } ;
}

std::string get_odd_digits( const std::string& number )
{
    std::string odd ;

    // range-based loop: http://www.stroustrup.com/C++11FAQ.html#for
    for( char c : number ) // for each character in the number
    {
        const int digit = c - '0' ; // '7' - '0' == 7 etc.
        if( digit%2 == 1 ) odd += c ;
    }

    return odd ;
}

std::string get_even_digits( const std::string& number )
{
    std::string even ;

    for( char c : number )
    {
        const int digit = c - '0' ; // '7' - '0' == 7 etc.
        if( digit%2 == 0 ) even += c ;
    }

    return even ;
}

int main()
{
    const std::string number = get_uint_str() ;

    std::cout << "\nnumber     : " << number << '\n'
              << "reversed   : " << reverse_digits(number) << '\n' ;

    const std::string odd_digits = get_odd_digits(number) ;
    if( odd_digits.empty() ) std::cout << "there are no odd digits\n" ;
    else std::cout << "odd digits : " << odd_digits << '\n' ;

    const std::string even_digits = get_even_digits(number) ;
    if( even_digits.empty() ) std::cout << "there are no even digits\n" ;
    else std::cout << "even digits: " << even_digits << '\n' ;
}

http://coliru.stacked-crooked.com/a/6e5241b73085ddec
@Theideasman
What do you mean??

@JLBorges
Hey thanks, but there are things I don't like about it. I want the output to be spaced out. And also need to show there are no odd or even. When there are none.
Output:
12345
The Original Number 1234
The number reversed 4 3 2 1
The even number 2 4
The odd number 1 3
y/Y to continue, any else to exit.

In order to that what would i do?
Last edited on
@Theideasman
What do you mean??


I was trying to get you think a bit about what you were doing - it was aimed at you coming up with the notion of some sort of count variable. JLBorges has these in the code, it's up to you to think about how to do your extra requirements.
Topic archived. No new replies allowed.