读取行文本文件,如果有逗号则拆分

时间:2017-05-09 09:20:57

标签: c++ split

文本文件内容

a,b,c,d,
efgh
ijk1

我希望存储在数组中,myArray [];预期输出将基于逗号分割:

myArray[0] = a;
myArray[1] = b;
myArray[2] = c;
myArray[3] = d;
myArray[4] = efgh;
myArray[5] = ijkl;

我做了什么

string myArray[100];
int array_count = 0;

ifstream file((path+dicfile).c_str());
std::string str;

while (std::getline(file, str,','))
{
    myArray[array_count] = str; // store those value in array
    cout << str << "\n";
    strings.push_back(str);
    array_count++;
}

我的输出已经完成了

myArray[0] = a;
myArray[1] = b;
myArray[2] = c;
myArray[3] = d;
myArray[4] = efghijkl;

1 个答案:

答案 0 :(得分:1)

以下代码是对每行原始代码拆分的补充,然后按逗号分隔该行:

string myArray[100];
int array_count = 0;

ifstream file((path+dicfile).c_str());
std::string line;

while (std::getline(file, line))
{
    std::istringstream iss(line);
    std::string str;
    while (std::getline(iss, str, ','))
    {
        myArray[array_count] = str; // store those value in array
        cout << str << "\n";
        strings.push_back(str);
        array_count++;
    }
}