比方說你的投入是這樣的:
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