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

C++ 如何将逗号分隔的值传递到多维数组中?,c++,arrays,multidimensional-array,C++,Arrays,Multidimensional Array,提供的文本文件的行数不确定,每行包含3个由逗号分隔的双精度字符。例如: -0.30895,0.35076,-0.88403 -0.38774,0.36936,-0.84453 -0.44076,0.34096,-0.83035 我想逐行从文件中读取这些数据,然后用逗号将其拆分,签名并保存在N×3数组中,我们称之为顶点[N][3],其中N表示文件中未定义的行数 到目前为止,我的代码是: void display() { string line; ifstream myfile ("File.tx

提供的文本文件的行数不确定,每行包含3个由逗号分隔的双精度字符。例如:

-0.30895,0.35076,-0.88403

-0.38774,0.36936,-0.84453

-0.44076,0.34096,-0.83035

我想逐行从文件中读取这些数据,然后用逗号将其拆分,签名并保存在N×3数组中,我们称之为顶点[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";
}

这是正确的吗?我如何访问我创建的向量的每个字段?比如在数组中? 我还注意到它们是string类型,如何将它们转换为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, ",\r\n" );
    fVal = (float)strtod( sVal, &pStop );
    Verticies[i][j++] = fVal;

    sVal = strtok( sVal + strlen(sVal) + 1, ",\r\n" );
    fVal = (float)strtod( sVal, &pStop );
    Verticies[i][j++] = fVal;

    sVal = strtok( sVal + strlen(sVal) + 1, ",\r\n" );
    fVal = (float)strtod( sVal, &pStop );
    Verticies[i][j] = fVal;

    i++;
    j = 0;
}

<> >编辑后的代码是正确的。您可以访问C++中的向量值,就像访问普通C++数组中的值一样。p> <关于如何将字符串转换为浮点的问题。在C++中,你可以直接使用STOF IE STOF0.88来实现这一点。

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

看看是否有一行不确定的行,你应该使用STD::向量,而不是普通的2D数组来存储数据。@ diutl uccg-我对C++是相当新的,在你提供的答案中,我应该做2个while循环?或者我在什么地方误解了?是/否-但如果列的宽度固定,则可以使用while/for并确保数据consistency@DieterL我已经根据你的建议编辑了我上面的问题,对吗?