首页 > 解决方案 > 如何在 getline() 中使用多个分隔符 (',' , '/n')?

问题描述

我正在尝试使用 fstream 在我的代码中读取文本文件。文本文件具有以下结构,

Main,Johnsons,4,4
Lake,Smiths,1,2
Orchid,Hendersons,3,8

我正在尝试执行以下操作。


Neighborhood n1;
ifstream houses;
houses.open("houses.txt");
string line;

string street;
string family;
int house;
int rooms;

int colptr = 1;

while (houses.good()) {
   getline(houses, line, ',');

        switch (colptr) {
        case 1: {
            col1 = line;
            colptr++;
            break;
        }
        case 2: {
            col2 = line;
            colptr++;
            break;
        }
        case 3: {
            col3 = stoi(line);
            colptr++;
            break;
        }
        case 4: {
            col4 = stoi(line);
            colptr = 1;
            House h(col1, col2, col3, col4);
            n1.addHouse(h);
            break;
        }
        default: {
            break;
        }
        }
    }

House 是一个使用 (string,string,int,int) 构造 House 的类,Neighborhood 类的方法 addHouse() 只是将 House 添加到房屋列表中。

该代码会引发错误,因为它试图将字符串转换为 int。我在第 4 次迭代中发现它会尝试将“4 Lake”转换为整数——这显然是做不到的。

如果在最后使用“,”格式化我的文本文件,则该代码有效

Main,Johnsons,4,4,

除了这对我不起作用,因为我得到的文本文件总是像开头显示的那样。

先感谢您!

标签: c++

解决方案


getline()您可以在嵌套循环中调用两次。第一个通常“逐行”读取输入,第二个在std::stringstream对象的帮助下用逗号“,”分割:

//...
while (houses.good()) {
    getline(houses, line); //use default getline() - line by line
    std::stringstream ss (line);
    std::string word;
    while (getline (ss, word, ',')) {
        //... the rest of code
        //...

推荐阅读