using ios::clear() with cin
using ios::clear() with cin
#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";
}
相关文章:
- C++中的cin.ignore()函数不适用于整个流
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- Problems with std::cin.fail()
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- 由cin中的字符串中未捕获空白引起的分割错误
- 在C++中使用Cin,我如何在1行中输入
- 将 cin 限制为只有一个
- cin >> int 给定一个字符串将 int 赋值为 0
- 这对"With a stackless coroutine, only the top-level routine may be suspended."意味着什么
- istream std::cin如何修改自定义istream缓冲区
- C++ 将 CIN 值存储到任何类型的数组中
- 为什么无论你输入什么,这"while(cin.get(str,3))"只运行一次?
- Boost.TEST with CLion: "Test framework quit unexpectedly"
- 避免碎片化的ClientHellos with OpenSSL (DTLS)
- Issues with Win32 ReadProcessMemory API
- Cin.get() issue with C++
- Error with while(cin)
- Input With Spaces正在阻塞下一个输入(使用cin)
- using ios::clear() with cin
- Problems with cin.getline()