После получения каждой строки из файла в вектор, цифры меняются или уничтожаются - PullRequest
0 голосов
/ 06 ноября 2019

После получения каждой строки из файла в вектор, цифры меняются или уничтожаются! 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;тогда это нормально, кстати, это дает мне -6.27744e + 66 за каждый первый [i] [j] и Yep IK, я могу легко написать, что у меня есть что-то подобное в моем "first.txt"

2
10
16
102
15

такУ меня есть матрица 2 * 2, которая дает нам 4 числа. но моя проблема заключается в получении первого [i] [j] из first.txt. результат должен быть таким

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

1 Ответ

0 голосов
/ 07 ноября 2019

Проблема с кодом, который я прокомментировал ниже. Цикл там читает числа из файла. Поэтому, когда выполняются другие циклы, достигнут конец файла, поэтому 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
...