954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How do I read a text file into a 2D vector?

Guys,

Your help will be appreicated in this matter.

i have to read a text file which has rows and columns into a vector. The text file could be of any size.

000000000
010010001
010010011
001001001

Now, how do I upload this text file on to a 2D vector?

so far, I have come up with this code:

ifstream in ("block.in");
ofstream out("block.out");

vector<vector<int>> block;
for (int i = 0; i < ???; ++i)
block.push_back(*istream_iterator<int>(in));


I don't know if this is correct at all. I am sorry guys, bear with me, I am new to the whole STL thing.

Any help would be appreciated.

Crouchinho
Newbie Poster
15 posts since Sep 2007
Reputation Points: 10
Solved Threads: 0
 

The rows would appear to be newline delimited; columns appear per character. Push back each column in a particular row, then when you are done with the row push it back.

Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

Thanks Dave, it gave me a breakthrough.
ok, so now I used the getline function to get the lines and insert into the vector, however, now that the row has been filled, how do i increment the columns?

This is the code I have so far, please bear with me.

#include <fstream>
#include <vector>							// for vector
#include <iomanip>							// for setprecision
#include <numeric>
#include <string>  
#include <sstream>
using namespace std;

void main()
{
	string s;
    ifstream in ("block.in");
    ofstream out("block.out");
	vector<vector<int>> block;

	while(getline(in,s))
		block.push_back(*istream_iterator<vector<int>>(in))

  
}


I know that I have to use a 'for' loop before I implement the push back statement. However, I do not know where to restrict or end my for loop. Got any ideas

Crouchinho
Newbie Poster
15 posts since Sep 2007
Reputation Points: 10
Solved Threads: 0
 

For input I'm kinda working with something like this.

std::vector<std::vector<int> > array;
      //
      // Input
      //
      std::string line;
      while ( std::getline(file, line) )
      {
         std::vector<int> row;
         char ch;
         std::istringstream ss(line);
         while ( ss >> ch )
         {
            row.push_back(ch - '0');
         }
         array.push_back(row);
      }
Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

Thanks for that as well, Dave. You are slowly becoming my favorite person ever!!

However, I wanted to ask you, what specific function does the char ch provide in this code?

and also would my code go tits up if I have this:

vector<int> row;
		char letter;
		istringstream ss (row);
		while(letter >> ss){
		row.push_back(*istream_iterator<int>(in));
		}
		block.push_back(row);


?

Crouchinho
Newbie Poster
15 posts since Sep 2007
Reputation Points: 10
Solved Threads: 0
 
However, I wanted to ask you, what specific function does the char ch provide in this code?

Well, I'm still trying to learn and remember, but I think it goes something like this...

A string is read intoline. To push back each represented int, first each character is extracted from the string (using the stringstream) and placed in ch. Then an int is created and pushed back.

Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

Ok Whose Who

youhadmeathello
Newbie Poster
1 post since Sep 2007
Reputation Points: 8
Solved Threads: 0
 

I now have a problem with the compiler on that code:

istringstream ss (row);
while(ch >> ss){


Noe, the first line gives me a C2664 error while the second line gives me tons of C2784 errors. Somehow I think we are implicitly trying to insert one variable type into another. How do you suggest I get rid of the compile errors?

Crouchinho
Newbie Poster
15 posts since Sep 2007
Reputation Points: 10
Solved Threads: 0
 

I was trying to come up with some fancy output using std::copy, a la this , but the syntax eludes me.

Relevant portions:

std::ostream& operator<< ( std::ostream &os, const std::vector<int> &row )
{
   std::copy(row.begin(), row.end(), 
             std::ostream_iterator<int>(std::cout, " "));
   return os;
}
std::copy(array.begin(), array.end(), 
                std::ostream_iterator<std::vector<int> >(std::cout, "\n"));


I'm gonna hafta break down and reconfigure STLfilt to try to discern my error messages.

Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 
while ( ss >> ch )
Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

Yes Dave!! It works!!

Man, I cannot thank you enough, you are a lifesaver.

Crouchinho
Newbie Poster
15 posts since Sep 2007
Reputation Points: 10
Solved Threads: 0
 

Also, Dave, by the by, would you know how to search for an element in the 2D vector?

I know I have to initialize iterators for both the rows and colums, but once they are initialized, how do I go about search for an element.

I dont know how the search function works in the STL.

I have the following code for the search algorithm:

int a = 1;
	vector< vector<int> >::iterator start = block.begin();
	vector< vector<int> >::iterator end = block.end();
	for( ; start != end ; ++start){
		vector<int>::iterator rowst = start->begin();
		vector<int>::iterator rowen = end->end();
		for( ; rowst != rowen; ++rowst){
        rowst = search(block.begin(), block.end(),vector<int>,a);

		}
	}
Crouchinho
Newbie Poster
15 posts since Sep 2007
Reputation Points: 10
Solved Threads: 0
 

I'll have to try to learn the search, I don't think I've tried that before.

I did find some stuff on c.l.c++ to help me fix my output a little.

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <iterator>

template< typename T >
std::ostream& operator<<(std::ostream& os, std::vector<std::vector<T> >& array)
{
   typedef typename std::vector<std::vector<T> >::const_iterator ci;
   for ( ci it = array.begin(); it != array.end(); ++it )
   {
      std::copy((*it).begin(), (*it).end(), std::ostream_iterator<T>(os, ", "));
      os << '\n';
   }
   return os;

} 

int main()
{
   std::ifstream file("file.txt");
   if ( file )
   {
      std::vector<std::vector<int> > array;
      //
      // Input
      //
      std::string line;
      while ( std::getline(file, line) )
      {
         std::vector<int> row;
         char ch;
         std::istringstream ss(line);
         while ( ss >> ch )
         {
            row.push_back(ch - '0');
         }
         array.push_back(row);
      }
      //
      // Output
      //
      std::cout << array << std::endl;
   }
   return 0;
}

/* my output
0, 0, 0, 0, 0, 0, 0, 0, 0, 
0, 1, 0, 0, 1, 0, 0, 0, 1, 
0, 1, 0, 0, 1, 0, 0, 1, 1, 
0, 0, 1, 0, 0, 1, 0, 0, 1, 
*/


[edit]I'll start here .

Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You