954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How to determine string from integer?

I have made a program to make a rectangle in a text matrix. It begins asking for width and height. The variable must be greater than 2 and a whole number. The only problem is if a user enters a character instead of a number, or a decimal instead of an integer 'm stuck in an infinite loop. How do you determine whether the input is a string, a double type or integer?

do{
cout << "\n\tEnter the width: ";
cin >> w1;
w2 = w1;
w2 = w1;
wf = w1;
inside = w1;
inside_c = w1;
inside-=2;
inside_c = inside;
cout << "\n\tEnter the height: ";
cin >> h;
hf = h;
h-=2;
cout << "\n" << endl;
if(w1<1 || h<1){
w1 = 0;
w2, wf, inside = w1;
h = 0;
hf = h;
cout << "Please enter a number greater than 2. \n" << endl;
error26 = true;}
else{
error26 = false;}
}while(error26 == true);

tedman102
Newbie Poster
5 posts since Aug 2011
Reputation Points: 10
Solved Threads: 0
 
How do you determine whether the input is a string, a double type or integer?


The state of cin will tell you if there was an error. If you ask for an integer, for example, and the operation fails, it's fairly safe to assume that the user typed the wrong thing. The conventional method is a loop that clears the stream state and discards remaining input every time this happens:

int x;

cout << "Please enter an integer value: ";

while (!(cin >> x)) {
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cout << "Invalid input. Please try again: ";
}

cout << "The integer value was " << x << '\n';

The down side to this method is that if the user types something like "123foo", the "123" will be successfully read and the "foo" will be left in the stream. Depending on your needs, that could be undesirable.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: