2017-02-24 136 views
0

我有一個多行文件。 行包含用逗號分隔的整數逐行讀取文件和標記行

在以下代碼中,它僅解析第一行,但不解析重命名行。任何有關我做錯了的見解?

void parseLines(std::ifstream &myfile){ 
    std::string line, token; 
    std::stringstream ss; 
    int i; 
    vector<int> r; 
    while(myfile) { 
    getline(myfile, line); 
    ss.str(""); 
    ss.str(line); 
    if(myfile){ 
     cout << "SS" << ss.str() << endl; 
     while (std::getline(ss, token, ',')){ 
     std::cout << token << std::endl; 
     } 
    } 
    } 
} 
+2

你想while'(getline(myfile,line))''。另外,在循環內部創建stringstream。 –

+0

如果這是在Windows上,那麼文件是否使用正確的CRLF行結尾格式化? – Potatoswatter

+0

在互聯網上搜索「stackoverflow C++讀取文件CSV」。 –

回答

2

約我做錯了任何見解?

需要重置ss的狀態,才能讀取第二行的數據。

更好的是,在循環內移動ss的構造。

雖然它,

  1. 通過while(getline(myfile, line))更換while(myfile)
  2. 在循環內移動token的聲明。

void parseLines(std::ifstream &myfile){ 
    std::string line; 
    int i; 
    vector<int> r; 
    while(getline(myfile, line)) 
    { 
     std::stringstream ss(line); 
     std::string token; 
     while (std::getline(ss, token, ',')){ 
     std::cout << token << std::endl; 
     } 
    } 
} 
2

這裏的問題是stringstream是不是本地的while循環。當您第一次讀取從stringstream讀取的流時會導致設置EOF標誌。如果你不清楚,那麼即使你加載更多,你也不會從中讀取更多信息。解決這個問題的最簡單方法是使循環體的局部變爲stringstream,這樣每次迭代時都可以使用新的變量,並且不必擔心清理標誌。這會使你的代碼看起來像

while(getline(myfile, line)) // also moved the line reading here to control when to stop the loop 
{ 
    std::stringstream ss(line); 
    while (std::getline(ss, token, ',')){ 
     std::cout << token << std::endl; 
    } 
}