Click here to Skip to main content
16,009,255 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This is for C++.
I want to store integers by rows and how many numbers are in each row may vary though.
So something like this won't work:
C++
int test[5] = {0};
	for( int i=0; i<5; i++)
		file >> test[i];

I was thinking of getline but that takes in strings though...

The input from a file:
1 3 250.00 
2 
15 1 1000.00
3 4 300.00
Posted
Updated 26-Nov-14 20:43pm
v3

hi,
Looking from the input format you have given,
you will have to do some text processing. I mean if you go with getline(), then after you have read a line, then you need to get the individual strings from the line and convert them to integers. It can be done and you need to figure this part out yourself.

An STL conatiner would be able to help you with the storage part.(what is STL)[^]

Simply put you can read the input from the text file.
Then use a std::map[^] alongwith a std::vector[^].
The map you can use is
C++
std::map<int,std::vector<int>>

so the key stores the number of integers in a row and the vector will store the actual integer values.


Then use iterators for traversing through the map instead of raw loops.
This might save you from 're-inventing the wheel'

hope this helps !!
 
Share this answer
 
v3
You should use a dynamic array, like a vector <vector <double> >.
Suppose your text file name is foo.txt then you might write something like this:
C++
#include <sstream>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;

int main()
{
  string line;
  ifstream ifs("foo.txt");

  vector < vector < double > > md; // dynamic array

  while ( getline(ifs, line).good())
  {
    md.push_back( vector <double >() );
    double d;
    stringstream ss(line);
    while ( ss.good() )
    {
      ss >> d;
      md.back().push_back(d);
    }
  }

  // show the collected items
  for (int r = 0; r < md.size(); ++r)
  {
    for ( int c = 0; c < md[r].size(); ++c)
    {
        cout << md[r][c] << " ";
    }
    cout << endl;
  }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900