Integer Occurences

Hello there,I have this piece of code that outputs the occurrences of an integer.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
       int Array[25];
	int Value;
	int intOccur=0;
	cout << "Enter 25 integers between 0-9: ";
	for (int i=0; i<25; i++)
	{
		cin >> Array[i];
		if (Array[i] > 9 || Array[i] < 0)
		{
	cout << "You're only supposed to enter integers between 0-9!" << endl;
	cin >> Array[i];
		}
                 //else if (!(cin>>Array[i]))
                     // { 
                      //   cout << "Only enter integers!" << endl;
                      //   cin >> Array[i];
                    //  }
	}


But I want to restrict the user to only enter integers, I tried if(!(cin>>Array[i])) but the output will be alot of

1
2
3
4
5
6
7
Only enter integers!
Only enter integers!
Only enter integers!
Only enter integers!
Only enter integers!
Only enter integers!
Only enter integers!

if i entered a floating value like 2.5.

how should i fix this?



Last edited on
You could do something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <limits>

void input(unsigned short& in) {
	while(true) {
		std::cout << "Enter:\t";
		if(std::cin >> in && (in>=0 && in<=9)) {break;}
		system("cls");
		std::cout << "Input not in range of (0 - 9)" << std::endl;
		std::cin.clear();
		std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	}
}

int main(int argc, char* argv[]) {
	unsigned short n = 0;
	input(n);

	std::cout << "n:\t" << n << std::endl;
	std::cin.get();
	std::cin.sync();
	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	return 0;
}


Note: I'm not advocating the use of system() or std::cin.sync() necessarily. For the sake of simplicity, I've elected to omit a more acceptable "clear screen" function.

If all the values are between 0 - 9 inclusive, an unsigned short should be more than enough to hold those values.
Basically, you pass an unsigned short by reference to the input function, which loops until valid input is provided by the user.
Floating point values will get implicitly cast to an unsigned short.

I'm here for any questions you may have.
Last edited on
Topic archived. No new replies allowed.