0

i have a problem with this code. Everything seems to be working fine but when you type something like this: 123aaaddfa123 then program will accept this as double value. Any ideas to avoid this problem? Thank you.

int main ()
{
   const char MAX = 5;
   cout << "Weight of your fishes (maximum 5)" << endl;
   double fishes[MAX];
   char count = 0;
   while (count < MAX)
   {
      cout << count + 1 << ". fish: " << endl;
      if (cin >> fishes[count])
          count++;
      else {
          cin.clear();
          if (cin.get() == 'q') //no more fishes = quit
              break;
          while (cin.get() != '\n') //clearing cin buffer
              continue;
      }
   }

if (count > 0) {
    double sum = 0;
    for (int i = 0; i < MAX; ++i) {
        sum += fishes[i];
    }
    cout << "Avarage weight of your " << (int)count << " fishes is: " << sum / count << " KG" << endl;
}

}

Bobul Mentol
  • 134
  • 1
  • 7
  • You can read in a `string` and convert this using [`std::stod()`](http://en.cppreference.com/w/cpp/string/basic_string/stof), which will throw an exception in such case. – πάντα ῥεῖ Aug 07 '15 at 08:37
  • @πάνταῥεῖ Really? According to cppreference, `std::stod` takes **as many characters as possible** to form a valid floating point representation and converts them to floating point value. – Lingxi Aug 07 '15 at 08:48
  • Look [here](http://stackoverflow.com/a/10349885/3410935) – Glapa Aug 07 '15 at 08:51

1 Answers1

0

This is a common question with input or conversion functions. The input >> operator will take as many characters as it can and leave the remaining part for last read. It is by design because it allows to read the samelines like 12.50$ or 12.50 $ with or without space between the number and the currency symbol :

double val;
std::string curr;
std::cin >> val >> curr;

If in you particuliar case you want to be able to detect extra characters after the numeric value, you must read the whole thing as a string. If it is in a line oriented input, you should use getline because a string input will stop at first blank character (space, tab, etc.)

Assuming you have a std::string str containing you input, you can do:

char *end;
double val = strtod(str.c_str(), &end);
if (*end != 0) {
    // there is something after last character used for the double
}
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252