編輯:就像我說的,我知道這個問題之前曾被問過,但沒有一個解決方案似乎爲我工作。請至少在投票之前閱讀帖子,不要投票。如何讓std :: cin讀取空格?
我知道這個問題已經被問過這個網站有點過,但我似乎無法掌握如何得到它與我的特別程序中工作。從本質上講,我創造了一個Mad Libs類型的遊戲,玩家必須進入某些事物才能將其融入到故事中。現在,如果用戶輸入中沒有空格,那麼這個工作就很完美了,但是,第二個用戶輸入一個空格,程序可以跳過整個問題。這裏是我的代碼:
int main(){
int selection;
//News Report Variables
std::string nrfullname;
std::string nrcrime;
std::string nradjective;
std::string nrtown;
std::string nrpluralnoun;
std::string nrnounnotplace;
std::string nrverb;
std::string nradjective2;
std::string nrfullname2;
std::string nrnounnotplace2;
std::cout << "Welcome to Mad Libs! Please, pick a story!" << std::endl;
std::cout << "1. News Report" << std::endl;
std::cin >> selection;
if (selection == 1) {
std::cout << "We need a full name of someone." << std::endl;
std::cin << nrfullname;
std::cout << "We need a crime." << std::endl;
std::cin >> nrcrime;
std::cout << "We need an adjective." << std::endl;
std::cin >> nradjective;
std::cout << "We need a town." << std::endl;
std::cin >> nrtown;
std::cout << "We need a plural noun." << std::endl;
std::cin >> nrpluralnoun;
std::cout << "We need a noun that is NOT a place." << std::endl;
std::cin >> nrnounnotplace;
std::cout << "We need a verb." << std::endl;
std::cin >> nrverb;
std::cout << "We need another adjective." << std::endl;
std::cin >> nradjective2;
std::cout << "We need a full name of someone else." << std::endl;
std::cin >> nrfullname2;
std::cout << "We need another noun that is NOT a place." << std::endl;
std::cin >> nrnounnotplace2;
}
正如你可能想象,大多數人會選擇把一個空間,它要求人的全名(我肯定知道我會)。要點是,如果他們把這個空間放在那裏,它就會跳過「犯罪」問題,並簡單地轉向形容詞問題。如果你們能告訴我如何讓這個工作正常工作,這將是有益的,因爲它一直在強調我一點點,我嘗試過的所有解決方案都讓問題變得更糟,或者沒有做任何事情來幫助解決問題。
感謝, MTS
你只需要'的std :: getline' ... – LogicStuff
注ŧ帽子'std :: cin'不會讀取任何內容。這是一個爲控制檯提供接口的對象。它是**函數**,你可以通過它讀取字符和值。 –