在获取从文件到矢量的每一行之后,数字将被更改或销毁

After Getting Every line from File to Vector, Digits are Changed or Destroyed

本文关键字:数字 之后 一行 文件 获取      更新时间:2023-10-16

获取从文件到矢量的每一行后,数字将被更改或销毁!!IDK为什么或如何销毁

ifstream first_matrix;
first_matrix.open("first.txt");
double temp;
int d;//Dimensions
vector<double> firstv(0);
first_matrix >> d;
//counter should be (d*d) + 1
//cuz we get dimension and here is 2
//and we want get 4 numbers(d*d) and the first line is dimension so (+ 1)
for ( i = 0; i < (d*d) + 1; i++)
{
first_matrix >> temp;
firstv.push_back(temp);
}
double** first = new double* [d];
for (i = 0; i < d; i++)
{
first[i] = new double[d]; 
for (j = 0; j < d; j++)
{
//as you can see I want to 
//put 4numbers of file.txt which is 10, 16, 102, 15
//into first[i][j]
first_matrix >> first[i][j];
std::cout << "Result [" 
<< i << "] ["
<< j << "] : "
<< first[i][j]; 
}

}

但是如果我删除first_matrix>>temp;那没关系顺便说一句,第一次[i][j]给我-6.27744e+66是的IK我可以很容易地写作我在我的"first.txt"中有这样的东西

2
10
16
102
15

所以我有一个矩阵,它是2*2,给我们4个数字。但我的问题是从first.txt中获取firt[i][j]。结果应该像这个

Result[0][0] = 10
Result[0][1] = 16
Result[1][0] = 102
Result[1][1] = 15

问题出在我下面评论的代码上。那里的循环正在从文件中读取数字。因此,当其他循环执行时,已到达文件末尾,因此返回0个值并将其存储到first中。

#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
ifstream first_matrix;
first_matrix.open("first.txt");
double temp;
int d;//Dimensions
vector<double> firstv(0);
first_matrix >> d;
// The problem is with the commented code below. It's reading the data from the
// from the file, which keeps the loops below from reading it.
//for ( int i = 0; i < (d*d) + 1; i++)
//  {
//    first_matrix >> temp;
//    firstv.push_back(temp);
//  }
double** first = new double* [d];
for ( int i = 0; i < d; i++)
{
first[i] = new double[d];
for (int j = 0; j < d; j++)
{
// This was putting zeroes into first[i][j]
first_matrix >> first[i][j];
std::cout << "Result ["
<< i << "] ["
<< j << "] : "
<< first[i][j] << std::endl;
}

}
}

上述代码输出:

Result [0] [0] : 10
Result [0] [1] : 16
Result [1] [0] : 102
Result [1] [1] : 15