【问题标题】:How to store nth column of comma delimited file in an array? [duplicate]如何将逗号分隔文件的第n列存储在数组中? [复制]
【发布时间】:2014-09-25 15:48:48
【问题描述】:

我有一个以以下格式存储数据的文件(这只是一个小示例):

AD,Andorra,AN,AD,AND,20.00,Andorra la Vella,Europe,Euro,EUR,67627.00
AE,United Arab Emirates,AE,AE,ARE,784.00,Abu Dhabi,Middle East,UAE Dirham,AED,2407460.00
AF,Afghanistan,AF,AF,AFG,4.00,Kabul,Asia,Afghani,AFA,26813057.00
AG,Antigua and Barbuda,AC,AG,ATG,28.00,Saint John's,Central America and the Caribbean,East Caribbean Dollar,XCD,66970.00
AI,Anguilla,AV,AI,AIA,660.00,The Valley,Central America and the Caribbean,East Caribbean Dollar,XCD,12132.00

我想存储每行的第二个字段,以便我的数组只包含国家名称,如下所示:

string countryArray[] = {"Andorra,United Arab Emirates", "Afghanistan", "Antigua and Barbuda", "Anguilla"}

但是每次我运行我的代码时,都会发生分段错误。这是我的代码:

countryArray[256];

if (myfile)
{
        while (getline(myfile,line))
        {
            std::string s = line;
            std::string delimiter = ",";

            size_t pos = 0;
            std::string token;
            short loop=0;

            while ((pos = s.find(delimiter)) != std::string::npos) 
            {
                  token = s.substr(0, pos);
                  s.erase(0, pos + delimiter.length());  

                  if (loop < 2)
                  {
                       loop++;
                  }
                  else
                  {
                       loop+=11;
                       countryArray[count] = token;
                       count++;
                  }

             }
        }
    }

【问题讨论】:

    标签: c++ arrays string token delimiter


    【解决方案1】:

    考虑使用std::istringstream。比如:

    while(getline(myfile, line))
    {
        std::istringstream iss(line);
    
        std::string data;
        getline(iss, data, ','); // get first column into data
        getline(iss, data, ','); // get second column into data
    
        countryArray[count] = data;
        ++count;
    }
    

    std::istringstream 的作用是让您将std::string 视为输入流,就像普通文件一样。

    您可以使用getline(iss, data, ','),它从流中读取到下一个逗号“,”并将其存储在std::string data

    编辑:

    还可以考虑使用std::vector 而不是数组。

    【讨论】:

    • 谢谢! +1 简单而优雅的解决方案:)
    【解决方案2】:

    您的段错误很可能是未初始化 count 的结果,然后将该变量用作 countryArray 数组的索引。因此,由于count 中的值未定义,您可能很容易超出数组的边界。

    【讨论】:

      猜你喜欢
      • 2014-12-14
      • 2011-05-30
      • 1970-01-01
      • 2020-10-23
      • 2012-03-19
      • 2020-10-10
      • 2010-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多