0
#include <iostream>
#include <sstream>

using namespace std;

int main(void) {
	string str;
	int i;

	cout << "Enter an integer: ";
	getline(cin, str);

	while(true) {
		stringstream ss(str);
		if (ss >> i) {
			break;
		}
		else {
			cout << "\nPlease enter a valid number: ";
			getline(cin, str);
		}
	}

	cout << "\nThe integer you entered is: " << i;

	return 0;
}

Output:

Enter an integer: vkjsdv

Please enter a valid number: djsvks

Please enter a valid number: sdjvn

Please enter a valid number: 324kjbkj

The integer you entered is: 324

How should I improve the code?
Secondly, how can I make the program display an error if a float is entered instead of type int?
Please suggest.

2
Contributors
1
Reply
2
Views
5 Years
Discussion Span
Last Post by zeroliken
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.