using ios::clear() with cin

using ios::clear() with cin

本文关键字:with cin clear ios using      更新时间:2023-10-16
#include <iostream>
int main() {
    int arr[4];
    for(int I = 0; I != 4; ++i) {
        std::cin >> arr[i];
        if(std::cin.fail()) {
            std::cin.clear();
            --i;
            break;
        }
    }
    for (auto u : arr)
        std::cout << u << 'n';
}

我不明白为什么这段代码不工作。我想再次将std::cin作为arr的元素,以防std::cin.fail()返回true。

break将终止循环。那不是你想要的。

还请注意,您没有从流中删除违规字符,因此您的下一个问题将是无限循环。

但是,即使删除了错误的字符,也可能会陷入无限循环,因为输入流中可能根本没有四个有效的整数。

这里有一个解决方案,简单地在循环中更新i

#include <iostream>
#include <cstdlib>
int main()
{
  int arr[4];
  for(int i = 0; i != 4; /* this field intentionally left empty */)
  {
    std::cin >> arr[i];
    if(std::cin) // did the read succeed?
    {
      ++i; // then read the next value
    }
    else
    {
      if (std::cin.eof()) // if we've hit EOF, no integers can follow
      {
        std::cerr << "Sorry, could not read four integer values.n";
        return EXIT_FAILURE; // give up
      }
      std::cin.clear();
      std::cin.ignore(); // otherwise ignore the next character and retry
    }
  }
  for (auto u : arr)
    std::cout << u << 'n';
}

但是整个事情变得脆弱,输入的解释可能与用户预期的不同。如果遇到无效输入,最好放弃:

#include <iostream>
#include <cstdlib>
int main()
{
  int arr[4];
  for (auto& u: arr)
    std::cin >> u;
  if (!std::cin) // Did reading the four values fail?
  {
    std::cerr << "Sorry, could not read four integer values.n";
    return EXIT_FAILURE;
  }
  for (auto u: arr)
    std::cout << u << "n";
}