【问题标题】:How can i pass comma separated values into a multidimensional array?如何将逗号分隔值传递给多维数组?
【发布时间】:2015-03-31 19:27:36
【问题描述】:

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

-0.30895,0.35076,-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";

}

这是正确的吗?以及如何访问我创建的向量的每个字段? (例如在数组中)? 我还注意到这些是字符串类型,我怎样才能将它们转换为浮点类型? 谢谢(:

【问题讨论】:

  • 如果行数不确定,您应该使用std::vector,而不是普通的二维数组来存储数据。
  • @DieterLücking 我对 C++ 相当陌生,在您在链接中提供的答案中,我应该执行 2 个 while 循环吗?还是我误会了什么地方?
  • 是/否 - 但如果您有固定宽度的列,您可以使用 while/for(并确保数据一致性)
  • @DieterLücking 我根据您的建议编辑了上面的问题,是否正确?

标签: c++ arrays multidimensional-array


【解决方案1】:

有很多方法可以解决这个问题。就个人而言,我会实现一个链表来将从文件中读取的每一行保存在它自己的内存缓冲区中。读取整个文件后,我会知道文件中有多少行,并使用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, ",\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;
}

【讨论】:

    【解决方案2】:

    编辑后的代码是对的。你可以在c++中访问一个向量值,就像你访问一个普通的c++数组中的值一样。像classdata[i]你可以在这里找到更多。 Vector reference

    关于将字符串转换为浮点数的问题。在 c++ 中,您可以使用 stof 直接执行此操作,即 stof(-0.883) 您可以在此处再次找到参考 string to float

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

    【讨论】:

      猜你喜欢
      • 2023-03-30
      • 2016-06-22
      • 2015-06-23
      • 1970-01-01
      • 2013-11-16
      • 1970-01-01
      • 2019-10-12
      • 2016-02-07
      • 1970-01-01
      相关资源
      最近更新 更多