-
chars and numbers in C++
hello, this is my first few weeks of coding, and i was hoping you fine people could give me some help (no one else wants to).
i have a simple program to find the length of a hypotenuse, now the problem is that when the user inputs a letter or word instead of a number, the program loops continuously. how do i get the program to ignore letters and words and take only integers?
here is the source if it helps:
int main()
{
int x, y;
cout<<"Please give me the two legs of the triangle."<<endl;
cout<<"First leg: "<<endl;
cin>>x;
cout<<endl<<"Second leg: "<<endl;
cin>>y;
cout<<endl<<"one moment please..."<<endl;
cout<<"the hypotenuse length is "<<sqrt(x*x+y*y)<<endl<<endl;
return 0;
}
-
firstly, get used to putting your code between [ code ] and [ /code ] tags (without the spaces)...
secondly.. here's a hint
Code:
#include <iostream.h>
#include <math.h>
#include <stdlib.h>
int main()
{
char buffer[12];
int x, y;
cout << "Please give me the two legs of the triangle." << endl;
do
{
cout << "First leg: " << endl;
cin.getline(buffer, sizeof(buffer));
x = atoi(buffer);
} while(x == 0);
do
{
cout<<endl<<"Second leg: "<<endl;
cin.getline(buffer, sizeof(buffer));
y = atoi(buffer);
} while(y == 0);
cout << endl << "one moment please..." << endl;
cout << "the hypotenuse length is " << sqrt(x * x + y * y) << endl << endl;
return(0);
}
the program is not complete.. but it's nearly there.. i didn't want to finish it for you because you wouldn't learn anything from it!
good luck
U.
-
Thanks for the help, i appreciate it! now i'm gonna figure out how to truncate the string to the size of the buffer so the error doesn't repeat....don't tell me yet! i'll get it....maybe. thanks again!
-
Code:
int num;
if(cin >> num)
{
cout << "It's a number!\n";
}
else
{
cout << "It's not a number!\n";
}