如何在数组中存储以逗号分隔的文件的第n列
How to store nth column of comma delimited file in an array?
我有一个文件,它以以下格式存储数据(这只是一个小示例):
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
中的值是未定义的,因此很容易超出数组的边界。
相关文章:
- 如何将 txt 文件中的行分隔为组件C++
- 无法通过空白将文本文件行分隔为矢量
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 如何在 C++ 中将文件中的逗号分隔数字读取到数组中?
- 读取制表符分隔的文件时出现问题 C++
- 如何更新和删除文本文件中的特定逗号分隔值?C++
- 如何将逗号分隔的文件读取为 2D int 数组?
- 读取带有分隔C++的文件
- 嵌套结构,从由空行分隔的文件中读取数据
- 如何逐行从文件中获取单词,并在C++中用分号分隔?
- 如何从文件中读取用空格分隔的数字
- 使用 fstream 在空格分隔文件中查看下一项(不仅仅是一个字符)的方法
- C++将分隔文件导入矢量
- C++ 在关键字段上联接两个管道分隔文件
- 当数据包含空格时,如何将制表符分隔文件的内容加载到C++字符串的 2D 向量中
- C++ 读取分隔文件并创建对象
- C++:读取分隔文件并存储在结构中
- 如何读取分隔文件的最后一行
- 如何在 Xcode 中分隔文件类
- visual c++6-用c++编辑管道分隔文件