昨天写一个超级无敌基础的题结果栽在输入上, 就是这个
int i1;
double d1;
string s1;
cin >> i1;
cin >> d1;
getline(cin, s1);
然后run的时候发现s1
直接被跳过了,单独cout了s1
后发现他的值好像变成了\n
???一搜才发现好像是getline()
把回车键当作我的input了???解决办法就是getline()
前面加上一句cin.ignore()
ignore()
是input stream下的一个函数,官方文档上它的作用是Extract and discard characters。
std::istream::ignore
istream& ignore (streamsize n = 1, int delim = EOF);
Extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim.
The function also stops extracting characters if the end-of-file is reached. If this is reached prematurely (before either extracting n characters or finding delim), the function sets the eofbit flag.
Internally, the function accesses the input sequence by first constructing a sentry object (with noskipws set to true). Then (if good), it extracts characters from its associated stream buffer object as if calling its member functions sbumpc or sgetc, and finally destroys the sentry object before returning.
n
是提取的最大字符数, 在之前的问题中, 只需要忽略一个\n
, 就使用默认就好了。有时候使用到cin.ignore(numeric_limits<streamsize>::max(),)
这样的代码,这就表示流的大小没有上限,提取的字符数没有上限。dim
是分隔字符,一旦遇到便停止提取。(EOF:end of file)