开发者

Input validation for Integer and Double data types

Because there was an error in the code when I po开发者_StackOverflow社区sted 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


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

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


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜