簡體   English   中英

C ++:Getline在第一個空格處停止讀取

[英]C++: Getline stops reading at first whitespace

基本上我的問題是我試圖從.txt文件中讀取數據,其中包含數字和注釋,並將每一行存儲到字符串向量中,但我的getline函數停止讀取第一個空白字符,所以注釋如(*)評論*)被分解成

str[0] = "(*";
str[1] = "comment";
str[2] = "*)";

這是我的getline函數的代碼塊看起來像:

int main() {
string line;
string fileName;
cout << "Enter the name of the file to be read: ";
cin >> fileName;

ifstream inFile{fileName};

istream_iterator<string> infile_begin {inFile};
istream_iterator<string> eof{};
vector<string> data {infile_begin, eof};
while (getline(inFile, line))
{
    data.push_back(line);
}

這就是.txt文件的樣子:

101481
10974
1013
(* comment *) 0
28292
35040
35372
0000
7155
7284
96110
26175

我無法弄清楚為什么它不讀全行。

這是因為您的代碼沒有使用std::getline來讀取輸入文件。

如果你仔細查看你的代碼,你會發現在你到達那一點之前,你的代碼在文件上構造了一個istream_iterator<string> ,並通過傳遞它,並將結束的istream_iterator<string>值傳遞給vector '構造函數,這有效地將整個文件(一次一個以空格分隔的單詞)吞入向量中。

當事情進入getline循環時,整個文件已經被讀取,並且循環完全沒有。 對於目前的狀況,你的getline並沒有真正做任何事情。

完全擺脫涉及istream_iterator的東西,簡單地讓getline完成它的工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM