2014-02-22 57 views
1

我遇到了一個與我的程序有關的問題。我正在構建一個金字塔程序,以更好地理解C++中的循環結構。 的問題是,當我建立並運行此,我得到:Do While While:永不停止的循環問題

cout << "\nPlease enter the number of lines for your pyramid: "; 
    cin >> height; 

,我輸入一個隨機字符,如「K」,它不斷地啓動(上房)循環:

cout << "ERROR: Please enter a value between 3 and 25!" << endl; 

我的問題:爲什麼它不斷循環? 有什麼可以實施來解決這個問題?

#include <iostream> 
#include <limits> 

using namespace std; 


void draw(int height) 
{ 
    for(int line = 0;line<=height;line++) 
    { 
     int spaces = height - line; 

     for(int j=1;j<=spaces;j++) 
     cout<<" "; 
     for(int i=1;i<=line*2+1;i++) 
     cout<<"+"; 
     cout<<"\n"; 
    } 
} 


int main() 
{ 
    int height; 
    do{ 
    cout << "\nPlease enter the number of lines for your pyramid: "; 
    cin >> height; 
    if(height>3 && height<25)draw(height); 

    else{ 
    cout << "ERROR: Please enter a value between 3 and 25!" << endl; 
    } 
    }while(height<3 || height>25); 
    cout << "\n"; 

    return 0; 
} 

我已經研究並沒有發現類似的問題,最常見的問題似乎是人們不設置他們的條件。

+0

你是不是測試的讀取輸入的結果。 – chris

+0

你期待一個'int',你爲什麼輸入'K'? – herohuyongtao

+1

@herohuyongtao - 用戶有時會輸入錯誤的東西 –

回答

2

的問題是,流輸入者>>將僅嘗試讀取輸入有效的爲您所輸入的類型:

int i; 
std::cin >> i; 

將只讀取整數值。如果失敗的話,將可以對與std::cin::fail()

int i; 
std::cin >> i; 
if (cin.fail()) 
    throw std::invalid_argument("Expected an int, got some other junk"); 

但是留下的輸入流中的輸入,讓你使用的各種機制中的一種繞過它進行測試的標誌。

最簡單的方法是使用std::getline來讀取輸入的行。

#include <string> 
#include <iostream> 
#include <cctype> 
#include <cstdlib> 

int main() { 
    std::string input; 
    int i = 0; 

    while (std::cin.good()) { 
     std::cout << "Enter a number between 3 and 25: "; 
     std::getline(std::cin, input); 
     if (input.empty()) // blank lines 
      continue; 
     if (isdigit(input[0])) { 
      i = atoi(input.c_str()); 
      if (i < 3 || i > 25) { 
       std::cout << "Invalid number, " << input << '\n'; 
       continue; 
      } 
      // valid input, stop the loop 
      break; 
     } 

     std::cout << "Unrecognized/non-numeric input: \"" << input << "\"\n"; 
    } 

    if (i == 0) // we left the loop because cin.good() was false 
     return 0; 

    std::cout << "You entered " << i << '\n'; 
} 

現場演示:http://ideone.com/KRHM3V

0

如果輸入有效,您將驗證。請與下面的代碼..

if(!(cin >> height)) 
{ 
    //print invalid input 
    break; 
} 

你也可以檢查cin.fail()

0

你需要閱讀height

見後檢查fail位 - fail bit

此設置,如果它是無法讀取整數。然後你需要吃一些輸入併發出一條消息

2

這是因爲您已聲明heightint,每當看到cin正在進入跳過沒有采取輸入char。所以輸入保持在輸入緩衝器中並且height保持其較舊值。在這種情況下,它的垃圾值和它的意外不在3和25之間。因此,無限循環。

使用,如果你想打破如果輸入一個非整數cin.fail()

int Item; 
cin >> Item; 
while (! cin.fail()) 
    { 
    Process(Item); 
    cin >> Item; 
} 

編輯:根據您的評論添加答案,輸入一個字符串。檢查每個位置的非數字。如果它是一個有效整數,則使用atoi()將其轉換爲整數。

+0

好的很好解釋。我期望用戶輸入一個3到25之間的整數,我的目標是:如果用戶在3-25之外鍵入一個字母或數字,它將提供一個錯誤。這是一個簡單的修復,使int爲char,但程序不再起作用。 – Kelsey