矢量不推回矢量(C ++)

时间:2014-10-18 13:56:27

标签: c++ matrix vector fopen scanf

我正在尝试读取文件并将文件内容分配到向量向量(矩阵)。 问题是它似乎没有做我需要它。 我也不太熟悉矢量,所以请原谅任何明显的错误:P

#include <stdio.h>
#include <vector>
#include <string.h>

void readfile(const char* filename,
    std::vector< std::vector<float> >& output)
{
    std::vector<float> vec123(3);
    char buff[80];
    FILE* myfile;
    myfile = fopen(filename, "r");

    while(fgets(buff, sizeof(buff), myfile) != NULL) {
        sscanf(buff, "%f %f %f", vec123[0], vec123[1], vec123[2]);
        output.push_back(vec123);
    }
    fclose(myfile);
}

这是我的主要内容:

int main() //yes, stdio.h, vector, "readfile" and string were included
{
    std::vector< std::vector<float> > myvec;
    readfile("myfile.txt", myvec); //file exists in my folder, valid
    printf("%f\n", myvec[2][2]);   //valid numbers for the file I'm reading
    return 0;
}

问题是,如果它没有给myvec分配任何内容,printf会发生段错误,但它确实会分配myvec,因为无论我从它请求什么有效对象,它都会打印出一个零浮点数。我知道一个简单的方法来做到这一点,没有2D矢量麻烦,但遗憾的是我的数学库是针对矩阵优化的。 myfile包含类似“2.2 3.14159 1.0换行符9.3 2.2 2.2换行符......”

1 个答案:

答案 0 :(得分:1)

应该是:

sscanf(buff, "%f %f %f", &vec123[0], &vec123[1], &vec123[2]);

因为sscanf将指针作为参数。

相关问题