如何在数组中存储以逗号分隔的文件的第n列

How to store nth column of comma delimited file in an array?

本文关键字:分隔 文件 数组 存储      更新时间:2023-10-16

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

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++;
                  }
             }
        }
    }

考虑使用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而不是数组。

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