-1

この質問を投稿したときにコードにエラーがあったため、良い質問ではありません。削除して、正しい解決策へのリンクに置き換えました。

入力検証の正しい解

4

2 に答える 2

1

cin.getline(buffer、'\ n'); <-間違っています。バッファサイズが必要です。

cin.getline(buffer, 10000, '\n');
于 2011-10-09T10:13:38.943 に答える
1

ここでの最も簡単な修正は、'cin.getline()' 呼び出しに制限を設定して、バッファーがオーバーフローしないようにするか、代わりに文字列クラスなどを使用するように切り替えることです。

#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;
}
于 2011-10-09T03:13:07.553 に答える