-2

Values from txt file

I have a values from a .txt file, and I want to store in a variable. In the first row in the file I have 13 values, also in others rows, and I want to store in the next form:

vector<vector<double>> x;

--first row

x[0][0] has the value of the first row and first col
x[0][1] has the value of the first row and the second col
x[1][0] has the value of the second row and the first col... and successively
Galik
  • 47,303
  • 4
  • 80
  • 117

1 Answers1

0

[Edit]

I'm not sure I'm helping you with this answer, since you didn't provide a problem, you did not say anything about what you tried, and what failed.

You should not expect people to just find a solution to your problem, I was just interested to do it, so I just posted my findings.

But this is not how this forum should work, programming is about learning, and if you just ask without trying nor explaining what your thought process was until now you will not learn.

Anyway, read the answer from which this one is inspired, there are some key elements to learn from.

[/Edit]

This code is inspired by this answer, that should be helpful for you to understand key concepts of C++.

Explanation for the emplace_back vs push_back.

Explanation for the Range-based for loop: "for (auto i : collection)"

#include <vector>
#include <string>
#include <fstream>
#include <sstream>
#include <iterator>
#include <cassert>
#include <iostream>

int main()
{
    std::vector< std::vector<double> > values;

    std::ifstream ifs; 
    std::string line; 
    ifs.open("test.txt"); 
    while(getline(ifs,line)) 
    {
        std::istringstream is(line); 
        std::vector<double> ns; 
        std::copy(std::istream_iterator<double>(is) 
                , std::istream_iterator<double>()  
                , std::back_inserter(ns));

        assert(ns.size() > 1); //throw something

        values.emplace_back(std::vector<double>(ns.begin(), ns.end()));  
    }

    for (auto line : values)
    {
        for (auto value: line)
        { 
            std::cout << value << " "; 
        }
        std::cout << std::endl;
    }
}
Community
  • 1
  • 1
vianney
  • 161
  • 6
  • Please don't encourage those who cannot be bothered to put in a little bit of their own effort first. – Disillusioned May 25 '16 at 05:35
  • I know but I had no time earlier to explain why I did answer. – vianney May 25 '16 at 05:52
  • 1
    Make sure you include a space between the two '>' s in your nested declaration of vectors, otherwise it can mistake it for the '>>' of 'cin'. – JFed-9 May 25 '16 at 06:25
  • I don't see the point since it can't compile before c++0x/c++11 with my use of emplace_back and auto. But it's true i should have precised that, thank you for noticing it. – vianney May 25 '16 at 06:55