如何将逗号分隔的值传递到多维数组中

How can i pass comma separated values into a multidimensional array?

本文关键字:数组 值传 分隔      更新时间:2023-10-16

提供的文本文件的行数不确定,每行包含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类型?谢谢(:

有很多方法可以解决这个问题。就我个人而言,我会实现一个链表,将从文件中读取的每一行保存在自己的内存缓冲区中。一旦读取了整个文件,我就会知道文件中有多少行,并使用strtokstrtod处理列表中的每一行以转换值。

这里有一些伪代码可以让你开始:

// 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)直接执行此操作,您可以在此处再次找到浮动的引用字符串

祝你好运,希望这能有所帮助:)