[英]cin.get() is taking input from previous cin.get()
我對此非常陌生,正在嘗試為 CLI 冒險游戲編寫一個簡單的商店界面。
我遇到的問題是在cin.get()
的使用之間。 我讀過另一篇文章,但不明白在說什么。 有人可以像我 5 歲那樣解釋嗎?
我在MainMenu()
中使用一次cin.get()
) 來等待Enter繼續。 如果玩家除了按Enter 鍵之外做任何其他事情,這會懲罰玩家的健康。
然后我前進到Introduction()
,在這里我嘗試使用相同的技巧,但它攜帶來自MainMenu()
function 的cin.get()
的輸入。
main()
中的其他代碼只是跟蹤角色的健康狀況,並在它通過另一個 function 達到 0 時停止程序。
#include <iostream>
#include <ctime>
#include <string>
using namespace std;
int MainMenu()
{
cout << "\nPress the ENTER key\n";
char Input = cin.get();
if (Input == '\n')
{
return 0;
}
else if (Input != '\n')
{
cout << "I meant ONLY the ENTER key... Oh well its your health pool.\n";
CharHealth(-2);
cout << "You took 2 damage. \nYou now have " << CharHealth(0) << "Health.\n";
return 0;
}
}
int Introduction()
{
cout << "you awake in a puddle, walk to town. \nPress [ENTER]";
char Input = cin.get();
if (Input != '\n')
{
cout << "\nfor real?\nTake Another 2 Damage\nwhat did you think?... Idiot" ;
CharHealth(-2);
return 0;
}
else
{
return 0;
}
}
int main()
{
MainMenu();
Introduction();
while (CharHealth(0) > 0)
{
cout << "winner";
return 0;
}
cout << "\n You died. idiot.";
return 0;
}
不要評判我講的故事,現在一切都還只是占位符。
我的控制台剛剛顯示:
Press the ENTER key asdf I meant ONLY the ENTER key... Oh well its your health pool. You took 2 damage. You now have 1Health. you awake in a puddle, walk to town. Press [ENTER] for real? Take Another 2 Damage what did you think?... Idiot You died. idiot. C:\Users\KR's\Documents\text Shop>
cin.get()
一次讀取 1 個char
。 因此,例如,如果用戶輸入asdf
,那么下一個cin.get()
將讀取並返回a
,將sdf
留在cin
的輸入緩沖區中。 然后下一個cin.get()
將讀取並返回s
,將df
留在cin
的輸入緩沖區中。 等等。 您的代碼沒有考慮到這一點。 cin
中只有 1 個輸入緩沖區,正如您所期望的,沒有每個函數的輸入緩沖區。
如果用戶沒有輸入您想要的內容,請使用cin.ignore()
丟棄不需要的輸入。 例如:
...
#include <limits>
...
int MainMenu()
{
cout << "\nPress the ENTER key\n";
char Input = cin.get();
if (Input != '\n')
{
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // <-- ADD THIS
cout << "I meant ONLY the ENTER key... Oh well its your health pool.\n";
CharHealth(-2);
cout << "You took 2 damage. \nYou now have " << CharHealth(0) << "Health.\n";
}
return 0;
}
int Introduction()
{
cout << "you awake in a puddle, walk to town. \nPress [ENTER]";
char Input = cin.get();
if (Input != '\n')
{
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // <-- ADD THIS
cout << "\nfor real?\nTake Another 2 Damage\nwhat did you think?... Idiot" ;
CharHealth(-2);
}
return 0;
}
cin.get()
只讀取一個字符,將其他輸入的東西留在 stream 上。
似乎您想閱讀直到\n
被閱讀。 可以這樣做:
int MainMenu()
{
cout << "\nPress the ENTER key\n";
int count = 0;
while (cin.get() != '\n') count++;
if (count == 0)
{
return 0;
}
else if (count != 0) // we won't need this if statement, but I respect you
{
cout << "I meant ONLY the ENTER key... Oh well its your health pool.\n";
CharHealth(-2);
cout << "You took 2 damage. \nYou now have " << CharHealth(0) << "Health.\n";
return 0;
}
}
(警告:如果我們在換行符之前得到 EOF,這段代碼將陷入無限循環)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.