c++ - 如何将逗号分隔文件的第 n 列存储在数组中?

标签 c++ arrays string token delimiter

<分区>

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

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 而不是数组。

关于c++ - 如何将逗号分隔文件的第 n 列存储在数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25097200/

相关文章:

java - 从应用程序中包含的文件加载 android 数组

c# - 将 bytearray 保存到 SQL Server 中的 VarBinary 列仅插入一个字节

string - Makefile:返回字符串的前两个字符

c++ - 从 SDL 库的函数返回的指针

c++ - 在 C++ 中返回当前对象 (*this)?

javascript - 如何将多维数组转换为这种格式

python - 需要洞察力 : Using python I am using a regular expression to capture sample restaurant sales data to categorize and convert it to JSON from a . pdf

c - 你好,我正在编写一个 C 程序来获取给定字符串中字符的位置

c++ - 我可以在 qt Creator 中使用带有 try catch 语句的断点吗?

c++ - 用VS2015编译共享库 : "this client is not compatible with the paired build agent"