【发布时间】:2015-06-08 15:24:30
【问题描述】:
我正在编写一个程序,它从一个文本文件中读取一个数组,该文本文件既有普通整数,也有多个科学计数法数字,格式为:#.#####E##。以下是输入 .txt 文件的几行示例:
21 -1 0 0 501 502 0.00000000000E+00 0.00000000000E+00 0.17700026409E+03 0.17700026409E+03 0.00000000000E+00 0. -1.
21 -1 0 0 502 503 0.00000000000E+00 0.00000000000E+00 -0.45779372796E+03 0.45779372796E+03 0.00000000000E+00 0. 1.
6 1 1 2 501 0 -0.13244216743E+03 -0.16326397666E+03 -0.47746002227E+02 0.27641406353E+03 0.17300000000E+03 0. -1.
-6 1 1 2 0 503 0.13244216743E+03 0.16326397666E+03 -0.23304746164E+03 0.35837992852E+03 0.17300000000E+03 0. 1.
这是我的程序,它只是读取文本文件并将其放入一个数组(或者更具体地说,一个向量的向量):
vector <float> vec; //define vector for final table for histogram.
string lines;
vector<vector<float> > data; //define data "array" (vector of vectors)
ifstream infile("final.txt"); //read in text file
while (getline(infile, lines))
{
data.push_back(vector<float>());
istringstream ss(lines);
int value;
while (ss >> value)
{
data.back().push_back(value); //enter data from text file into array
}
}
for (int y = 0; y < data.size(); y++)
{
for (int x = 0; x < data[y].size(); x++)
{
cout<<data[y][x]<< " ";
}
cout << endl;
}
// Outputs the array to make sure it works.
现在,此代码在文本文件的前 6 列(这些列完全是整数)上运行良好,但随后它完全忽略了第 6 列及更高的每一列(这些列包含科学记数法数字)。
我尝试将向量重新定义为 double 和 float 类型,但它仍然做同样的事情。如何让 C++ 识别科学记数法?
提前致谢!
【问题讨论】:
-
你能显示你正在阅读的文件的前几行吗?
-
样本输入,样本输出。最好在 testcase 中。不明白为什么这么难。
-
您正在尝试将浮点数读入 int 并且失败了。
-
好吧,我编辑了帖子以包含一段数据文件。我也尝试过使用浮点类型,但不幸的是这也不起作用。