whonnock
whonnock

Reputation: 45

How to ignore float if a comma is present?

I'm writing a program that takes a float as input (For example asking for height in cm). Is there a way to ignore the input given by the user if there is a comma instead of a dot?

For example: If the user inputs 1,90 instead of 1.90 I want it to stop and say that, that is not a valid number and that the format requirement is not satisfied.

I'll include my code below so that you get a general idea of what I'm trying to do.


cout << "\nPlease provide your height is cm separated by a dot: ";
while(!(cin >> height)){
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cout << "\nInvalid input. Try again: ";
}

Upvotes: 0

Views: 218

Answers (1)

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29985

A clean way to do that would be to read the input as string, do all your validation and parsing, then reject/accept the input accordingly. Here's a simplified example:

#include <string>
#include <iostream>

int main() {
  std::cout << "Enter value: ";
  std::string input;
  std::cin >> input; // get input

  // Make sure it has no commas
  if (input.find(',') != input.npos) {
    std::cout << "Wrong format\n";
    return 1;
  } 

  double d;

  // Parse and do other validations
  try {
    d = std::stod(input);
  } catch (std::exception const& e) {
    std::cout << "Error " << e.what() << '\n';
    return 2;
  }

  // Happy ending
  std::cout << "You entered " << d << '\n';
  return 0;
}

Upvotes: 4

Related Questions