Domanda

Because there was an error in the code when I posted this question, it is not a good question. I have deleted and replaced it with a link to a correct solution.

Correct Solution for Input Validation

È stato utile?

Soluzione

cin.getline(buffer, '\n'); <-- is wrong, need buffer size.

cin.getline(buffer, 10000, '\n');

Altri suggerimenti

The simplest fix here is to set a limit on your 'cin.getline()' call so it doesn't overflow your buffer, or alternatively switch over to using a string class or some such like so:

#include <iostream>
#include <errno.h>

int main() {
  std::string buffer;
  double value;
  char* garbage = NULL;

  while (true) {
    std::cin >> buffer;
    std::cout << "Read in: " << buffer << std::endl;
    if (std::cin.good())
    {
      value = strtod(buffer.c_str(), &garbage);
      if (errno == ERANGE)
      {
          std::cout << "A value outside the range of representable values was returned." << std::endl;
          errno = 0;
      }
      else
      {
        std::cout << value << std::endl << garbage << std::endl;
        if (*garbage == '\0')
          std::cout << "good value" << std::endl;
        else
          std::cout << "bad value" << std::endl;
      }
    }
  }
  return 0;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top