如何将逗号分隔的值传递到多维数组中
How can i pass comma separated values into a multidimensional array?
提供的文本文件的行数不确定,每行包含3个用逗号分隔的双引号。例如:
-0.30895、0.30076、-0.88403
-0.38774,0.36936,-0.84453
-0.44076,0.34096,-0.83035
我想逐行从文件中读取这些数据,然后用逗号(,)符号将其拆分,并将其保存在一个N乘3的数组中,我们称之为Vertices[N][3],其中N表示文件中未定义的行数。
到目前为止我的代码:
void display() {
string line;
ifstream myfile ("File.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
// I think the I should do 2 for loops here to fill the array as expected
}
myfile.close();
}
else cout << "Unable to open file";
}
问题:我设法打开文件并逐行读取,但我不知道如何将值传递到请求的数组中。非常感谢。
编辑:我已经尝试根据我收到的以下建议修改我的代码:
void display() {
string line;
ifstream classFile ("File.txt");
vector<string> classData;
if (classFile.is_open())
{
std::string line;
while(std::getline(classFile, line)) {
std::istringstream s(line);
std::string field;
while (getline(s, field,',')) {
classData.push_back(line);
}
}
classFile.close();
}
else cout << "Unable to open file";
}
这是正确的吗?如何访问我创建的向量的每个字段?(例如在数组中)?我还注意到这些是字符串类型的,我如何将它们转换为float类型?谢谢(:
有很多方法可以解决这个问题。就我个人而言,我会实现一个链表,将从文件中读取的每一行保存在自己的内存缓冲区中。一旦读取了整个文件,我就会知道文件中有多少行,并使用strtok
和strtod
处理列表中的每一行以转换值。
这里有一些伪代码可以让你开始:
// Read the lines from the file and store them in a list
while ( getline (myfile,line) )
{
ListObj.Add( line );
}
// Allocate memory for your two-dimensional array
float **Vertices = (float **)malloc( ListObj.Count() * 3 * sizeof(float) );
// Read each line from the list, convert its values to floats
// and store the values in your array
int i = j = 0;
while ( line = ListObj.Remove() )
{
sVal = strtok( line, ",rn" );
fVal = (float)strtod( sVal, &pStop );
Verticies[i][j++] = fVal;
sVal = strtok( sVal + strlen(sVal) + 1, ",rn" );
fVal = (float)strtod( sVal, &pStop );
Verticies[i][j++] = fVal;
sVal = strtok( sVal + strlen(sVal) + 1, ",rn" );
fVal = (float)strtod( sVal, &pStop );
Verticies[i][j] = fVal;
i++;
j = 0;
}
编辑后的代码是正确的。您可以访问c++中的向量值,就像访问普通c++数组中的值一样。像classdata[i]
你可以在这里找到更多。矢量参考
至于您关于将字符串转换为浮点值的问题。在c++中,您可以使用stof ie stof(-0.883)
直接执行此操作,您可以在此处再次找到浮动的引用字符串
祝你好运,希望这能有所帮助:)
相关文章:
- 比较if语句中的数组值和int值
- 为什么我的排序算法会更改数组值
- C++ 如何将数组值解压缩为函数参数
- 在 C++ 中访问 JSON 数组值
- 如何在 c# 代码中通过引用调用时从 c++ dll 更新数组值?
- 为什么我的数组值与此处的全局变量不匹配?
- 如何通过 cython 将 numpy 数组列表传递给 C++
- 为什么我的数组值会更新为随机值?
- C++2D网格数组,从文件中读取和插入数组值
- property_tree获取字符串形式的数组值
- 将 2D 数组指针传递给 C++ 中的函数
- 如何将数组传递给函数,以便在更改该函数中的数组值时原始数组的值不会更改?
- CUDA 全局函数未正确添加某些索引的数组值
- 使用 cin 输入数组值
- C++不同内存位置中的默认数组值
- 为什么会出现一些垃圾而不是数组值?
- 如何在 c++ 中递增数组值?
- 使用指针传递数组值
- 计数在C 中相同数组值的发生
- 2D数组值像数组一样传递,0不打印