C++ 输入被切断
这个代码看起来很简单,对吗C++ 输入被切断,c++,string,input,output,iostream,C++,String,Input,Output,Iostream,这个代码看起来很简单,对吗 string password; cin.ignore(); getline(cin, password); cout << "The user inputted the password: " << password << endl; 字符串密码; cin.ignore(); getline(cin,密码); coutcin.ignore()忽略输入的下一个字符。这意味着secret中的s。我想,之所以有这个调用,是因为以前的g
string password;
cin.ignore();
getline(cin, password);
cout << "The user inputted the password: " << password << endl;
字符串密码;
cin.ignore();
getline(cin,密码);
coutcin.ignore()
忽略输入的下一个字符。这意味着secret
中的s
。我想,之所以有这个调用,是因为以前的getline
问题似乎跳过了输入(请参阅)。这仅适用于使用运算符>>
并事先留下换行符的情况。我建议改为:
getline(std::cin >> std::ws, password);
这将消除剩余空白的问题,而不会在没有空白时造成问题。您可以这样做
string password;
cout << "enter password:";
getline(cin, password);
cout << "The user inputted the password: " << password << endl;
字符串密码;
难道这就是ignore()
所做的-忽略一个字符。为什么你有cin.ignore()
?@chris噢,谢谢你,我对函数的工作原理有一个误解:)那是什么“std:ws”?不过剩下的我都有了,谢谢@AxelKennedal TechTutor,它提取前导空格。提取?你能从头到尾解释一下这条线是如何工作的吗?:)@AxelKennedal TechTutor,std::cin>>std::ws
读取开头的空白并将其丢弃。例如,如果您的输入缓冲区为\n\t Axel Kennedal\n
,则空格、制表符和换行符将被删除,输入缓冲区将保留为Axel Kennedal\n
。它的返回值是std::cin
,这是您传入的内容,但现在缓冲区缺少空格。然后,std::getline
继续读取,直到换行符像正常一样出现,但现在它没有得到输入开始时存在的任何空白。
string password;
cout << "enter password:";
cin >> password;
cin.clear();
cin.ignore(200, '\n');
cout << "The user inputted the password: " << password << endl;