【问题标题】:read line textfile and split if it got comma读取行文本文件,如果有逗号则拆分
【发布时间】:2017-05-09 09:20:56
【问题描述】:

文本文件内容

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;

【问题讨论】:

  • getline 与这些 args 得到你的行,直到下一个逗号或 eof
  • 如果输入数据正确,则说明最后两个字符串之间缺少逗号。
  • @GeorgeNewton 是的,风格是这样的,最后两个字符串会合并在一起,因为它之间没有逗号,但文本文件内容最初没有逗号...
  • 在这种情况下我没有看到问题 - 你的输出是正确的吗?
  • 所以你的要求不正确:它应该在 EOL 和逗号上分开。其他空格呢?

标签: c++ split


【解决方案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++;
    }
}

【讨论】:

  • 第 7 行;应该写 while (std::getline(file, line, ','))
猜你喜欢
  • 1970-01-01
  • 2014-10-05
  • 2023-01-18
  • 2011-09-08
  • 2018-05-04
  • 2011-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多