比方说你的投入是这样的:
2\n
line 0\n
line 1\n
然后cin>>test
后,有在顶部的空行:
\n
line 0\n
line 1\n
使用>>
只读取该位是感兴趣的(即int
)然后留下任何后面的流(在这种情况下,只是\n
但考虑一下,重新可能是线上的各种东西)。 getline
读取所有内容直至\n
然后从流中删除\n
。 所以第一getline
后,剩余的输入是:
line 0\n
line 1\n
cases[0]
和包含""
(即空字符串)。
那么接下来getline
后:
remaining input:
line 1\n
和
cases[0]: ""
cases[1]: "line 0"
然后循环停止,因为它已经读取2行。 这是错的。解决它是另一回事。我宁愿只是为了避免混合>>
和getline
。但是你可以做一些事情来清除流下的\n
。
编辑:您可能也做得很好,在std::vector读了(即文档可能会有点技术 - 搜索教程)和using namespace std;
的罪恶我放在一起修复它的一种方式。注意stoi
只是C++ 11。如果你没有这个可用,你可以尝试stringstream
与>>
或atoi
。
#include <iostream>
#include <vector>
#include <string>
int main()
{
int inLines = 0;
//std::cin >> inLines;
std::string countLine;
std::getline(std::cin, countLine);
try
{
inLines = std::stoi(countLine);
}
catch (...)
{
std::cout << "First line must be an integer\n";
return 1;
}
std::vector<std::string> lines(inLines);
for (int i = 0; i < inLines; ++i)
{
std::getline(std::cin, lines[i]);
}
for (auto & s : lines)
{
std::cout << s << '\n';
}
return 0;
}
给出解释错误的示例输出 – uba 2013-03-11 11:39:37
它是'>>'和'getline'的组合。在你输入int的大小后,剩下的行(实际上可能不包含任何内容)正被读入'cases [0]'中。我总是发现最简单的方法就是不混合使用'>>'和'getline'。 – BoBTFish 2013-03-11 11:41:04