简体   繁体   English

C++ ifstream 问题。我想从 a.csv 文件中读取“坐标”,但不知何故,代码读取了文件两次,并且输入了奇怪的数字

[英]C++ ifstream problem.I want to read “coordinates” from a .csv file but somehow the code reads the file twice and it puts wierd numbers

I have a problem trying to read coordinates from a.csv file to a 2d array, to use it as input to a linear regression model.I know how to read from a file to an array but i needed the informations of the file to be double and not string so I thought i should see what the output whould be.我在尝试从 a.csv 文件读取坐标到二维数组时遇到问题,将其用作线性回归 model 的输入。我知道如何从文件读取到数组,但我需要文件的信息双而不是字符串,所以我想我应该看看 output 应该是什么。 I can't get it right.The problem is that the file's lines are being read 30 times each one of them and i can't figure it out.我做错了。问题是文件的每一行都被读取了 30 次,我无法弄清楚。 The code is here:代码在这里:

    #include <iostream>
    #include <fstream>
    #include <sstream>
    #include <string>
    #include <cmath>
    #include <limits>
    #include <iomanip>
    #include <vector>
    using namespace std;


    int main()
    {
           cout<<setprecision(10);
           //vector<vector<double> > observ_matr;
           ifstream myfile("Salary_Data.csv");
           vector<vector<double> > vec;
           string line;
           while(getline(myfile,line))
           {
                  stringstream lineStream(line);
                  string cell;
                  vector<double> temp_vec;
                  while(getline(lineStream, cell, ','))
                  {
                          temp_vec.push_back(atof(cell.c_str()));
                  }
                  vec.push_back(temp_vec);
           }
           for(int i=0;i<vec.size();i++)
           {
                  for(int j=0;j<vec.size();j++)
                  {
                          cout<<vec[i][j]<<"\t\t";
                  }
                  cout<<endl;
           }
           //cout<<vec[1].size();

           return 0;
     }

"myfile" is this, this.csv file “myfile”就是这个,这个.csv文件

The output i am getting after running the code is this:运行代码后我得到的 output 是这样的:

The problem is here...问题就在这里...

    for (int j = 0; j < vec[i].size(); j++) // vec[i].size() instead of vec.size()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM