2015-01-16 71 views
1

的不輸出下一個實例我有以下代碼While循環並串

#include <iostream> 
#include <fstream> 
#include <string> 

int main(){ 
    std::string file = "words.txt"; 
    std::string word; 
    std::ifstream inFile; 
    std::string delimiter = ","; 
    inFile.open(file); 
    if (!inFile){ 
     std::cerr << "File not opened." << std::endl; 
    } 
    while (getline(inFile, word)){ 
     std::cout << word.substr(0, word.find(delimiter)) << " "; 
     word.erase(0, word.find(delimiter) + delimiter.length()); 
    } 
    inFile.close(); 
    std::cin.get(); 
} 

在這個循環的一個問題:

while (getline(inFile, word)){ 
     std::cout << word.substr(0, word.find(delimiter)) << " "; 
     word.erase(0, word.find(delimiter) + delimiter.length()); 
    } 

我收到的唯一輸出的第一子在輸出中形成"word1"

我已經在擦除函數後面的行中輸入了一個std::cout << word.substr(0, word.find(delimiter)),以確定該單詞是否仍然有字符,並且確實如此。 word是格式爲"word1","word2","word3",...,"lastword"的很長的字符串,我的分隔符是","

+4

你遍歷文件中的行,沒有結束的一行字。做'getline(inFile,word,',')',而不需要做任何'substr'業務。如果你需要迭代這些行中的行和單詞,你將需要嵌套循環。 –

回答

2

as @Joseph Mansfield在評論中說。你遍歷文件的行,而不是它的文字。

對於分詞,,您可以簡單地使用分隔符作爲getline的第三個輸入。

#include <iostream> 
#include <fstream> 
#include <string> 

int main(){ 
    std::string file = "words.txt"; 
    std::string word; 
    std::ifstream inFile; 
    char delimiter = ','; 
    inFile.open(file); 
    if (!inFile){ 
     std::cerr << "File not opened." << std::endl; 
    } 
    while (getline(inFile, word,delimiter)){ 
     std::cout << word << " "; 
    } 
    inFile.close(); 
    std::cin.get(); 
} 

以及用於讀取多行:

std::string line; 
while (getline(inFile, line)){ 
    std::stringstream stream(line); 
    while (getline(stream, word, delimiter)){ 
     std::cout << word << " "; 
    } 
} 
0

在您閱讀下一行的同時,使用getline(inFile,word)。因此現在包含下一個讀取