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";
}
如果您想再次閱讀,那麼爲什麼您要「斷開」循環? –
因此,它會再次運行具有相同值「i」的for循環。我想'break',因爲如果'cin.fail()'會再次返回true,我將有機會再次'cin'。我希望它運行,直到我會給它一個數字而不是一個字符,例如 – Tony
@Tony你不需要'break'。它將退出'for'循環。 –