while循环不输出子串的下一个实例

时间:2015-01-16 17:22:09

标签: c++

我有以下代码

#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",我的分隔符为","

2 个答案:

答案 0 :(得分:2)

@ 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 << " ";
    }
}

答案 1 :(得分:0)

在你用 getline(inFile,word)阅读下一行的情况下。因此, word 现在包含下一个读取