I'm quite a beginner on C++. I wanted to write a little program that just takes a number from the user typed to the console, runs a simple operation and returns the result. If the user enters something that can't be processed, I want the program to print an error message and ask the user again for an other input instead of printing out wrong results.
Since any input that is not a number will cause an error, I simply want to check if the user entered a number or something else. strtof offers the possibility to get the first character that couldn't be converted to a numeric value, hence I thought it would be a good idea, to first read in a character, convert it with strtof and then see if there is any character that couldn't be converted. If so, it should ask the user again.
My code looks like this:
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
float number;
char *endptr;
char userinput[256];
cout << "Please enter a number: ";
cin >> userinput;
number = strtof(userinput, &endptr);
while (*endptr != 0) {
cout << "Input was not a valid number. Please enter a number: ";
cin >> userinput;
number = strtof(userinput, &endptr);
}
// the actual program
// function(number) = ...
return(0);
}
Everything works fine, except when I enter something like "a b c d". In this case he program will print out four error messages instead of one. First I thought it is a problem with strtof, but it works. Literally, cin doesn't read "a b c d" as "a b c d" but as "a" then "b" then "c" and finally "d" because of the whitespaces.
Is there a way I can prevent my program from that strange behavior? Thanks a lot.

New Topic/Question
Reply




MultiQuote




|