【发布时间】:2014-10-18 13:56:26
【问题描述】:
我正在尝试读取文件并将文件的内容分配到向量(矩阵)的向量中。 问题是它似乎没有做我需要的事情。 我对向量也不太熟悉,所以请原谅任何明显的错误: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 newline 9.3 2.2 2.2 newline ...”的内容
【问题讨论】:
-
为什么在
c++中使用stdio.h和string.h? -
与其使用
char[]、sscanf等,我更推荐使用streams,这样更干净、更安全。 -
@Cyber 我可能会尝试,如果这是问题所在。 fopen 似乎是比 ofstream 等更好的解决方案。
-
正如您从 user2040251 的回答中看到的那样,类似 c 的函数适合初学者。如果您使用流,就不会像以前那样犯错误
-
你需要调试你的应用程序,而不是猜测。
标签: c++ matrix vector fopen scanf