• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 202
  • 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
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
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

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

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