khf*_*kek 2 c++ arrays notation
我正在编写一个程序,该程序从文本文件中读取数组,该文本文件既有普通整数,也有科学计数法形式的多个数字,其形式为:#.#####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.
Run Code Online (Sandbox Code Playgroud)
这是我的程序,它只是读取文本文件并将其放入数组(或更具体地说,向量的向量)中:
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.
Run Code Online (Sandbox Code Playgroud)
现在,这段代码对于文本文件的前 6 列(这些列完全是整数)工作得很好,但随后它完全忽略了第 6 列及更高的每一列(这些列包含科学记数法数字)。
我尝试将向量重新定义为 double 和 float 类型,但它仍然做同样的事情。如何让 C++ 识别科学记数法?
提前致谢!
改成int value;double value;并将向量更改为 double 而不是 int。
更好的是,由于您有三个声明必须全部同步到正确的类型,因此可以为该类型创建一个别名,如下所示:using DATA_TYPE = double;然后声明您的向量等:vector<vector<DATA_TYPE> > data;、DATA_TYPE value;等。这样,如果您更改数据的类型无论出于何种原因,所有向量和变量声明都会自动更新,从而避免此类错误。
| 归档时间: |
|
| 查看次数: |
5139 次 |
| 最近记录: |