初學程序員在這裏,我有問題的字符串輸入 結構的程序 - 我有問題,成功地存儲字符串 用戶輸入的年份,流派,和導演。我嘗試不使用cin >>與 getline,只使用get()和getline() - 但錯誤仍然存在 字符串輸入未正確存儲。 EX:如果用戶輸入選項'B', 並將年份字符串輸入「2015」存儲到字符串變量whatYear中,則其 會導致未正確存儲的錯誤。怎麼修?如何解決字符串用戶輸入而不使用cin.ignore()和clear() - C++?
#include <iostream>
#include <cctype>
#include <string>
void printYear();
void printGenre();
void printDirector();
using namespace std;
int main(){
char choice;
用戶將輸入選擇:'B'表示年份,'C'表示流派,'D'表示導演。
cout << "Hello movie'goer, please select one of the following choices:\n\n"
<< "B - Display movies in a specific year\n"
<< "C - Display movies in a specific genre\n"
<< "D - Display movies from a specific director\n\n"
<< "Enter your choice: ";
choice = cin.get();
//Input validation
while (toupper(choice) != 'B' && toupper(choice) != 'C' &&
toupper(choice) != 'D') {
cout << "Choice is invalid, the choice must be one of the following:'B', 'C', or"
<< " 'D'. Re-enter your choice: ";
choice = cin.get();
}
cout << endl << endl;
這是處理選擇的地方。 'B'將打印字符串年份輸入,'C'將打印字符串流派輸入,'D'將打印字符串導演的名稱輸入。
switch(choice)
{
case 'a':
case 'A': break;
case 'b':
case 'B': printYear(); break;
case 'c':
case 'C': printGenre(); break;
case 'd':
case 'D': printDirector(); break;
}
}
當選擇'B'輸入年份時,我無法將年份輸入存儲到字符串變量whatYear中。
void printYear()
{
string whatYear;
cout << "Enter a specific year: " << endl;
getline(cin, whatYear);
我檢查是否字符串輸入存儲成功,但它是一個失敗。
cout << "The input stored in string whatYear is: " << whatYear;
}
我在這裏也有同樣的問題,以及字符串輸入沒有被成功存儲到字符串變量whatGenre。
void printGenre()
{
string whatGenre;
cout << "Enter a specific genre: " << endl;
getline(cin, whatGenre);
cout語句在此處顯示不正確。
cout << "The input stored in string whatGenre is: " << whatGenre;
}
與其他兩個函數相同的問題。
void printDirector()
{
string whatDirector;
cout << "Enter a specific director " << endl;
getline(cin, whatDirector);
cout << endl << "The input stored in string whatGenre is: " << whatDirector;
}
請注意,Stack Overflow並不意味着作爲解決您的個人問題的幫助臺,而是作爲未來研究的常見問題資源。你曾經問過的問題已經被多次詢問過了,其中一個最有爭議的問答對已經包含了答案。因此我將你的問題標爲重複。 –