2015-09-27 132 views
0

對不起,如果這是一個簡單的問題,但我相當新的C++。任何我寫的方式和簡單的氣象站,接受用戶輸入,並最終打印出來。在這種特定情況下,用戶被要求以N,NE,NW ...等等的給定選項在風向輸入。我的問題是我可以有某種循環,如果他們沒有輸入適當的字符串值,就會顯示「無法再次嘗試」,並重新執行該過程。如何將用戶輸入限制爲某些字符串值?

下面是代碼:

//Asks the user to input the current wind direction and stores it as windDirection 

    cout << "Please enter the current wind direction(N, NE, NW, S, SE, SW, E, W), then press enter." << endl; 

    getline(cin, windDirection); 
+2

答案是肯定的。使用「while」循環,直到獲得有效的輸入。 –

+0

或者這個問題是一個微妙的建議,爲你寫代碼? –

+0

@PCLuddite不是真的,我很好奇,因爲我做了我認爲是一個while循環體面的嘗試,但它沒有工作,所以不知道如果可能。 – Christian

回答

0

這個while循環結束了我的工作,感謝那些誰幫助。它可能會更好,但它能完成這項工作!

//Asks the user to input the current wind direction and stores it as windDirection 
    while (cout << "Please enter the current wind direction(N, NE, NW, S, SE, SW, E, W), then press enter." << endl && 
       cin >> windDirection && windDirection != "N" && windDirection != "NE" && windDirection != "NW" && windDirection != "S" 
       && windDirection != "SE" && windDirection != "SW" && windDirection != "E" && windDirection != "W"){ 

    cout << "That is an Invalid wind direction input, try again.\n"; 
    cin.clear(); 
    cin.ignore(); 
      } 
相關問題