[英]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.