![](/img/trans.png)
[英]std::getline does not accept std::back_insert_iterator
[英]std::getline() does not accept empty input
我希望能够同时接受非空字符串和空字符串作为输入。 只要没有空输入,下面的代码就可以工作 - 这将导致代码只是等待输入而不是继续。 cin.ignore() 是它不跳过第一个输入所必需的(可能是因为我之前有其他使用 cin 的输入)。 假设 getline() 接受空字符串我错了吗?
std::cin.ignore(1,'\n');
std::vector<std::string> words(n, "");
for (int i = 0; i != n; ++i) {
std::getline(std::cin, words[i]);
}
我曾尝试在循环中使用 cin.clear() 和 cin.ignore() ,但它最终放弃了输入。 我应该怎么做才能解决这个问题?
最小可重现示例:
#include <iostream>
#include <vector>
int main() {
int n = 0;
std::cin >> n;
std::cin.ignore(1,'\n');
std::vector<std::string> words(n, "");
for (int i = 0; i != n; ++i)
std::getline(std::cin, words[i]);
for (int i = 0; i != n; ++i)
std::cout << words[i] << std::endl;
return 0;
}
这很简单:
#include <iostream>
#include <limits>
#include <vector>
int main( )
{
const std::size_t count { 5 };
std::vector<std::string> words( count, "" );
for ( std::size_t idx { }; idx != count; ++idx )
{
std::getline( std::cin, words[idx] );
std::cin.putback( '\n' );
std::cin.clear( );
std::cin.ignore( std::numeric_limits<std::streamsize>::max( ), '\n' );
}
std::cout << "\nwords:\n";
for ( const auto& word : words )
{
std::cout << '\'' << word << "' ";
}
}
样本输入/输出:
1
2
// here I skipped the third input
4
5
words:
'1' '2' '' '4' '5'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.