Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/149.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 输入被切断_C++_String_Input_Output_Iostream - Fatal编程技术网

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,密码);
cout
cin.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;