繁体   English   中英

输入被截断

[英]Input being chopped off

这段代码看起来很简单,对吧?

string password;
cin.ignore();
getline(cin, password);
cout << "The user inputted the password: " << password << endl;

好吧,由于某种原因,当我输入“secret”作为密码时,cout 只会产生“ecret” ,即每次都会删除第一个字符 为什么是这样?

cin.ignore()忽略输入的下一个字符。 这意味着s in secret 我想这个电话是因为之前getline似乎跳过输入的麻烦(见这个问题)。 这仅适用于使用operator>>并事先留下换行符的情况。 我建议改为:

getline(std::cin >> std::ws, password);

这将消除剩余空白的麻烦,并且在没有空白时不会引起问题。

你可以这样做..

string password;
cout << "enter password:";
getline(cin, password);
cout << "The user inputted the password: " << password << endl;

或者,您可以使用 cin 接收输入。 现在您可以使用 cin.ignore。

string password;
cout << "enter password:";
cin >> password;
cin.clear();
cin.ignore(200, '\n');
cout << "The user inputted the password: " << password << endl;

当您使用cin >>接收输入时,最好使用cin.clear()cin.ignore() 但是,如果您使用的是getline() ,则似乎没有必要使用cin.ignore()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM