Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 201
  • Last Modified:

simple if question

I have a program which asks the user for a number (float) but if the user inputs a char instead of a float it sends my program into a loop which never ends.  I want to know if there is a way to read what the user inputs and if it is a char then it will tell the user they must enter a number and repeats the orginal question.

basic example

 
float x;
cout << "enter number";
cin >> x;

if (x != char) // problem is here

cout << "Number is: " << x;
else
cout << "you must enter a number";
0
onestar
Asked:
onestar
  • 4
  • 2
1 Solution
 
nietodCommented:
The way around this is the let the user enter a character string.  Then try to convert the string to a number (integer or real, as needed).  

As I'm not very familia with C I/O, I won't submit code examples, unless no one else can help (unlikely).
0
 
nietodCommented:
By the way the character string can be converted to an integer with atoi() or to a floating point with atof().
0
 
nietodCommented:
What the heck.  I found what I needed.

char InputLine[100];

cin.getline(InputLine,100);
// You can test input line for invald characters here.  (Let me know if you need help on this.)  
float x = atof(InputLine);
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
nietodCommented:
Not that you can test the strign entered by the use for invalid characters, but you don't have to.  the conversion fucntions start at the beginning of the string and stop converting when they reach an invalid character.  So if the user enters "123abc" it will convert to 123.  If the user enters "abc" it will convert to 0.  This may or may not be acceptable to you as is.
0
 
kellyjjCommented:
dang nietod,  you beat to the punch.  I was trying to answer the question when you did.  Damn it all to hell!!!  hehehe
0
 
kellyjjCommented:
Do you mean to have an "if" in there?  like "if (x)"?
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now