2 Replies - 527 Views - Last Post: 28 October 2009 - 03:32 PM Rate Topic: -----

#1 5gon12eder  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 28-October 09

Reading and Verifying Number from Console

Posted 28 October 2009 - 02:36 PM

Hello everybody,

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.

Is This A Good Question/Topic? 0
  • +

Replies To: Reading and Verifying Number from Console

#2 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6092
  • View blog
  • Posts: 23,612
  • Joined: 23-August 08

Re: Reading and Verifying Number from Console

Posted 28 October 2009 - 03:22 PM

cin stops on whitespace. You should use cin.getline().
Was This Post Helpful? 1
  • +
  • -

#3 5gon12eder  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 28-October 09

Re: Reading and Verifying Number from Console

Posted 28 October 2009 - 03:32 PM

Thanks, now everything works as it should. I tried getline() before, but I was using it wrong.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1