C++ on number input only

closed account (STR9GNh0)
i tried, do while, while and etc..

i can't just simply input numbers (any int numbers). if not numbers, cin, prompt to re-enter again.

i even tried isDigit still not good to go.

eg..

1
2
3
4
5
6
7
int num;

do
{
    cin >> num;
}while (num != 0);


any help would be appreciated
Does this work?
1
2
3
4
5
6
7
int num;
while (1)
{
  cin >> num;
  if (num == 0)
    break; 
}


Make sure you are not entering any chars like commas or periods.
closed account (STR9GNh0)
nope, not working
closed account (3hM2Nwbp)
This should work
* Edit * - reference link: http://www.cplusplus.com/reference/iostream/istream/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

int main()
{
	int value;
	std::cout << "Enter 0-9" << std::endl;
	std::cin >> value;
	while(std::cin.fail())
	{
		std::cout << "Invalid Entry\nEnter 0-9" << std::endl;
		std::cin.clear();
		std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
		std::cin >> value;
	}
	std::cout << "Entered: " << value << std::endl;
        return 0; //Edit # 2 - Forgot my return !
}
Last edited on
One of the last things he shows here might be what you are looking for:

http://www.youtube.com/watch?v=0e1ia9wfPnQ
Last edited on
closed account (STR9GNh0)
thanks Luc Lieber

it works.. but eg, if i entered 11a it will register the 11 in it.
Posting this to tell you that I didn't copy the right url, I edited in the right one into my reply :P
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

int main ()
{
	bool intEntered = false;
	char input[255] ;
	int number;

	do{
	cout<<"Input numbet: ";
	cin >> input;
	string s = input;
	number = atoi(s.c_str());
	if ( number == 0 )
	cout << "Null is not alowed :) ";
	else
		intEntered = true;

	}while(!intEntered);
}


Here dude... :)))
Topic archived. No new replies allowed.