2013-02-20 75 views
1

我正在完成一項實驗室任務,其中提示用戶輸入他們希望訂購的魚的類型並輸入每磅價格。在報告打印之前,需要提示用戶輸入魚類的類型和價格兩次。第一次嘗試期間循環失敗

問題是程序在循環的第一個實例完成之前結束。 (編寫代碼的方式報告中的標題將打印兩次,但是在說明中。)

代碼如下,非常感謝您的幫助。

#include <iostream> 
#include <iomanip> 
#include <string> 

using namespace std; 

int main() 
{ 
     float price; 
    string fishType; 
    int counter = 0; 

    // Change the console's background color. 
    system ("color F0"); 

    while (counter < 3){ 

    // Collect input from the user. 
    cout << "Enter the type of seafood: "; 
    cin >> fishType; // <------ FAILS AT THIS POINT. I GET THE PROMPT AND AT THE         "ENTER" IT DISPLAYS THE REPORT 

    cout << "Enter the price per pound using dollars and cents: "; 
    cin >> price; 

    counter++; 
    } 

    // Display the report. 
    cout << "   SEAFOOD REPORT\n\n"; 
    cout << "TYPE OF    PRICE PER" << endl; 
    cout << "SEAFOOD     POUND" << endl; 
    cout << "-------------------------------" << endl; 
    cout << fixed << setprecision(2) << showpoint<< left << setw(25) 
     << fishType << "$" << setw(5) << right << price << endl; 

    cout << "\n\n"; 
    system ("pause"); 

    return 0; 
} 
+3

你能告訴它的確切位置結束?在結束之前是否收到提示? – 2013-02-20 23:12:54

+2

TIme運行調試器,看看哪一行失敗... – 2013-02-20 23:13:13

回答

7

換行字符將不會被讀取消耗,使用std::istream::operator>>(float),該price的:

cin >> price; // this will not consume the new line character. 

新行字符的下一個讀期間存在,使用operator>>(std::istream, std::string))成fishType

cin >> fishType; // Reads a blank line, effectively. 

,然後將該意所述用戶輸入是下fishType將被讀(並且未能)的price,因爲它不會是有效的float值。

要更正ignore(),直到讀取price後的下一個新行字符。例如:

cin.ignore(1024, '\n'); 
// or: cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 

總是檢查輸入操作的狀態以確定它們是否成功。這是很容易實現:

if (cin >> price) 
{ 
    // success. 
} 

如果fishType可以包含然後使用operator>>(std::istream, std::string)是不恰當的,因爲它會停在第一個空格閱讀空間。使用std::getline()來代替:

if (std::getline(cin, fishType)) 
{ 
} 

當用戶進入輸入新的行字符將被寫入stdin,即cin

 
cod\n 
1.9\n 
salmon\n 
2.7\n 

在循環的第一次迭代:

cin >> fishType; // fishType == "cod" as operator>> std::string 
       // will read until first whitespace. 

cin現在包含:

 
\n 
1.9\n 
salmon\n 
2.7\n 

則:

cin >> price; // This skips leading whitespace and price = 1.9 

cin現在包含:

 
\n 
salmon\n 
2.7\n 

則:

cin >> fishType; // Reads upto the first whitespace 
       // i.e reads nothin and cin is unchanged. 
cin >> price; // skips the whitespace and fails because 
       // "salmon" is not a valid float. 
+0

你能解釋一下你的意思嗎? – 2013-02-20 23:14:41

+0

不知道我跟着。 – 2013-02-20 23:18:35

+0

價格是一個int,不會搶到換行符。需要抓住,作爲一個單獨的字符串閱讀我相信。 – 2013-02-20 23:20:16

相關問題