[英]Input being chopped off
This code looks simple, right?这段代码看起来很简单,对吧?
string password;
cin.ignore();
getline(cin, password);
cout << "The user inputted the password: " << password << endl;
Well for some reason when i type in "secret" as the password the cout results in only "ecret" , ie it is chopping off the first character every time.好吧,由于某种原因,当我输入“secret”作为密码时,cout 只会产生“ecret” ,即每次都会删除第一个字符。 Why is this?
为什么是这样?
cin.ignore()
ignores the next character of input. cin.ignore()
忽略输入的下一个字符。 That means the s
in secret
.这意味着
s
in secret
。 I imagine the call is there because of previous troubles of getline
seeming to skip input (see this question ).我想这个电话是因为之前
getline
似乎跳过输入的麻烦(见这个问题)。 This only applies when operator>>
is used and leaves a newline beforehand.这仅适用于使用
operator>>
并事先留下换行符的情况。 I recommend instead doing:我建议改为:
getline(std::cin >> std::ws, password);
This will remove troubles over leftover whitespace and not cause problems when there is none.这将消除剩余空白的麻烦,并且在没有空白时不会引起问题。
You can just do this..你可以这样做..
string password;
cout << "enter password:";
getline(cin, password);
cout << "The user inputted the password: " << password << endl;
Alternatvely , you can use cin to receive inputs.或者,您可以使用 cin 接收输入。 Now you can use cin.ignore.
现在您可以使用 cin.ignore。
string password;
cout << "enter password:";
cin >> password;
cin.clear();
cin.ignore(200, '\n');
cout << "The user inputted the password: " << password << endl;
It is good to use cin.clear()
and cin.ignore()
when you are receiving inputs using cin >>
.当您使用
cin >>
接收输入时,最好使用cin.clear()
和cin.ignore()
。 However, if you are using getline()
, it seems unnecessary to use cin.ignore()
.但是,如果您使用的是
getline()
,则似乎没有必要使用cin.ignore()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.