获取用户输入时出现问题
这是代码:
cout << "Please enter the file path: ";
string sPath;
getline(cin, sPath);
cout << "Please enter the password: ";
string sPassword; getline(cin, sPassword);
问题是,当我运行它时,它显示“请输入文件路径:”,然后显示“请输入密码:”,然后等待密码。它似乎完全跳过了第一个“getline()”。
稍后编辑:是的,之前已经完成了一些输入操作。
int iOption = 0;
while (iOption == 0)
{
cout << "(E/D): ";
switch (GetCH())
{
case 'E':
iOption = 1;
break;
case 'e':
iOption = 1;
break;
case 'D':
iOption = 2;
break;
case 'd':
iOption = 3;
break;
default:
break;
}
}
以及 GetCH() 的代码,以防有人问起。
char GetCH ()
{
char c;
cin >> c;
return c;
};
Here's the code :
cout << "Please enter the file path: ";
string sPath;
getline(cin, sPath);
cout << "Please enter the password: ";
string sPassword; getline(cin, sPassword);
Problem is, when I run it it displays "Please enter the file path: " then it displays "Please enter the password: " and then waits for the password. It seems to completely skip the first 'getline()'.
Later edit: Yes there are some input operations done before.
int iOption = 0;
while (iOption == 0)
{
cout << "(E/D): ";
switch (GetCH())
{
case 'E':
iOption = 1;
break;
case 'e':
iOption = 1;
break;
case 'D':
iOption = 2;
break;
case 'd':
iOption = 3;
break;
default:
break;
}
}
And the code for GetCH() in case anyone asks.
char GetCH ()
{
char c;
cin >> c;
return c;
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看来在调用
getline
时为GetCH
输入的行的其余部分仍然保留在缓冲区中,即至少有一个\n< /code> 这就是您在第一个
getline
调用中阅读的内容。程序不会阻止等待用户输入,因为仍排队等待读取的部分行可以满足getline
请求。考虑修改您的
GetCH
函数以读取整行。例如(恐怕完全未经测试):
It looks like the rest of the line that was input for
GetCH
still remains in the buffer at the time that you callgetline
, i.e. at least a\n
and this is what you are reading in the firstgetline
call. The program doesn't block waiting for user input because thegetline
request can be satisfied by the partial line still queued for reading.Consider modifying your
GetCH
function to read whole lines as well.E.g. something like (totally untested, I'm afraid):
您需要清除输入流中可用的任何内容,如下所示
You need to clear whatever available in input stream like below
我在 while 循环之前有一个 cin.clear() ,并修改了 GetCH 选项以获取带有“getline”的整个字符串,并且仅返回第一个字母。
现在它就像一个魅力。感谢大家的帮助。
I have a
cin.clear()
before the while loop and have modified the GetCH option to get a whole string with 'getline' and only return the first letter.It works like a charm now. Thanks to everyone for the help.