2012-11-12 30 views
2

我試圖創建一個簡單的溫度轉換程序,允許用戶根據需要將溫度轉換多次,直到他們決定通過輸入字母'e'結束程序。除了用戶輸入字母'e'的部分外,代碼中的其他所有內容都可以工作。如果我把最後一個else語句拿出來,程序就在循環的開頭再次開始。如果我在else語句中輸入字母'e',則else語句會認爲它是無效輸入,並且不會結束程序。在while循環中接受用戶輸入

#include <iostream> 

using namespace std; 

float celsiusConversion(float cel){  // Calculate celsius conversion 
    float f; 

    f = cel * 9/5 + 32; 
    return f; 
} 

float fahrenheitConversion(float fah){ // Calculate fahrenheit conversion 
    float c; 

    c = (fah - 32) * 5/9; 
    return c; 

} 
int main() 
{ 
    char userInput; 

     while (userInput != 'e' or userInput != 'E') // Loop until user enters the letter e 
     { 

      cout << "Please press c to convert from Celsius or f to convert from Fahrenheit. Press e to end program." << endl; 
      cin >> userInput; 


      if (userInput == 'c' or userInput == 'C') // Preform celsius calculation based on user input 
       { 
        float cel; 
        cout << "Please enter the Celsius temperature" << endl; 
        cin >> cel; 
        cout << cel << " Celsius is " << celsiusConversion(cel) << " fahrenheit" << endl; 
       } 
      else if (userInput == 'f' or userInput == 'F') // Preform fahrenheit calculation based on user input 
       { 
        float fah; 
        cout << "Please enter the Fahrenheit temperature" << endl; 
        cin >> fah; 
        cout << fah << " Fahrenheit is " << fahrenheitConversion(fah) << " celsius" << endl; 
       } 
      else // If user input is neither c or f or e, end program 
       { 
        cout << "Invalid entry. Please press c to convert from Celsius, f to convert from Fahrenheit, or e to end program." << endl; 
       } 
     } 
    return 0; 
} 
+0

只有標準庫才能響應單個按鍵。您至少需要閱讀整個*行*的輸入。爲此,SO上已經有成千上萬的重複數據。 –

+1

這可能會使do-while循環更有意義。 – jrajav

回答

0

我會想辦法讓2發生在你的代碼:

while (userInput != 'e' && userInput != 'E') 

,在此之前只是「別人「(以防止在退出程序時出現錯誤信息):

else if (userInput == 'e' or userInput == 'E') 
      { 
       break; 
      } 
1

你的意思while(userInput != 'e' && userInput != 'E')

的 '或' 版本始終是真實的

+0

,以便結束程序,但不打印出else行之前。有關如何解決這個問題的任何建議? 編輯:沒關係,我只是將last else語句更改爲: else if(userInput!='e') – Tydis