2015-08-30 22 views
-1
#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.fail()返回true,我想再次std::cin的元素arr使用ios :: clear()與cin

+1

如果您想再次閱讀,那麼爲什麼您要「斷開」循環? –

+0

因此,它會再次運行具有相同值「i」的for循環。我想'break',因爲如果'cin.fail()'會再次返回true,我將有機會再次'cin'。我希望它運行,直到我會給它一個數字而不是一個字符,例如 – Tony

+0

@Tony你不需要'break'。它將退出'for'循環。 –

回答

0

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