I am still trying to come up with a simple solution where i add lines of words to a 2d array so i can pick an array element and display what is in that array

I can read the lines of text and output which words are on which line but i need to store them in an array

I know people are going to say to use vectors but in this occasion i need to use arrays

How do i add the words to a 2D array? I tried a for loop but that didn't work

#include <iostream>
#include <sstream>
#include <fstream>
#include <string>

using namespace std;

int main ()
{

	//number of rows and cols
	string words[4][4];
	//read in file
    ifstream inFile ("data.txt");
    string line;
	
    int linenum = 0;
    while (getline (inFile, line))
    {
		//displayes the linenum
		cout << "\nLine #" << linenum << ":" << endl;
		linenum++;
		
		//read the line
		istringstream linestream(line);
		string item;
		int itemnum = 0;
		//splits on the whitespace
		while (getline (linestream, item, ' '))
		{	
			//dsiplay the words
			cout << "Item #" << itemnum << ": " << item << endl;
			itemnum++;
		}
    }

    return 0;
}

Recommended Answers

All 9 Replies

To make things simpler, you can read the data in as a 1D array (pointer), but still be able to access the data through a 2D array. Like this:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
  //number of rows and cols
  string words[4][4];

  // Pointer to first element of words (acts as 1D array)
  string *wordsPtr = &words[0][0];

  //read in file
  ifstream inFile( "data.txt", ios::in );

  // Calculate number of words to retrieve
  size_t numWords = sizeof(words) / sizeof(string);

  for (size_t i = 0; i < numWords; ++i) {
    inFile >> wordsPtr[i];
    cout << "Line #" << i << ": " << wordsPtr[i] << '\n';
  }

  return 0;
}

Hope this helps.

commented: exactly what i wanted +1

Many thanks......exactly what i needed.

Is there a way where i could create an array for row number and an array for column numbers so i can display what row and column a certain array element is at. Say i was looking for a specific word, i could see which row/column it was in?

I have had a go at trying to extend this program and creating a seperate class to be included which displays the lines but i've got errors. It may be simple but i can't see why.

test.cpp(8) : error C2628: 'Matrix' followed by 'int' is illegal (did you forget a ';'?)
test.cpp(9) : error C3874: return type of 'main' should be 'int' instead of 'Matrix'
test.cpp(24) : error C2228: left of '.displayMatrix' must have class/struct/union
d:\program files\microsoft visual studio 9.0\vc\GeneExp.hpp(13) : error C2065: 'numWords' : undeclared identifier
d:\program files\microsoft visual studio 9.0\vc\GeneExp.hpp(14) : error C2065: 'inFile' : undeclared identifier
d:\program files\microsoft visual studio 9.0\vc\GeneExp.hpp(14) : error C2065: 'wordsPtr' : undeclared identifier
d:\program files\microsoft visual studio 9.0\vc\GeneExp.hpp(15) : error C2065: 'wordsPtr' : undeclared identifier

the main program

#include <iostream>
#include <fstream>
#include <string>
#include "GeneExp.hpp"

//using namespace std;

int main()
{
	//number of rows and cols
	string words[4][4];
	
	// Pointer to first element of words (acts as 1D array)
	string *wordsPtr = &words[0][0];
	
	//read in file
	ifstream inFile( "data.txt", ios::in );
	
	// Calculate number of words to retrieve
	size_t numWords = sizeof(words) / sizeof(string);
	
	Matrix newMatrix(size_t numwords);
	
	newMatrix.displayMatrix();
	
	/*for (size_t i = 0; i < numWords; ++i) {
		inFile >> wordsPtr[i];
		cout << "Line #" << i << ": " << wordsPtr[i] << '\n';
	}*/

	cout << "array pointer [1][1] is:" << words[1][1] << endl;
	cout << "array pointer [2][4] is:" << words[2][4] << endl;
	cout << "array pointer [3][3] is:" << words[3][3] << endl;

    return 0;			
}

the class i tried creating

#include <string>
#include <iostream>

using namespace std;

class Matrix {

	public:
		Matrix (size_t numwords) {};
		~Matrix() {};
		
		void displayMatrix(size_t numwords) {
			for (size_t i = 0; i < numWords; ++i) {
			inFile >> wordsPtr[i];
			cout << "Line #" << i << ": " << wordsPtr[i] << '\n';
		}
	}
}

Quite a few errors here.


1 - You're missing a semi-colon after the curly brace at the end of your Matrix class.

class Matrix {
public:
  Matrix(size_t numwords) { };
  ~Matrix() {};

  void displayMatrix(size_t numwords) {
    for (size_t i = 0; i < numWords; ++i) {
      inFile >> wordsPtr[i];
      cout << "Line #" << i << ": " << wordsPtr[i] << '\n';
    }
  }
}[B]; // Fergot semi-colon here.[/B]

2 - Variables are case sensitive in C++, therefore, numwords is not the same as numWords as you have done in your displayMatrix member function.

void displayMatrix(size_t numwords) {
  for (size_t i = 0; i < [B]numWords[/B]; ++i) { [B]// Change to numwords[/B]
  inFile >> wordsPtr[i];
  cout << "Line #" << i << ": " << wordsPtr[i] << '\n';
}

3 - Both inFile and wordsPtr are only accessible in the main scope. You can fix this in a couple of ways, one way would be to make these variables global (accessible anywhere), or better - to add the parameters to the displayMatrix function:

void displayMatrix(size_t numwords, [B]std::ifstream &inFile, string *wordsPtr[/B]) {
  for (size_t i = 0; i < numWords; ++i) {
    inFile >> wordsPtr[i];
    cout << "Line #" << i << ": " << wordsPtr[i] << '\n';
  }
}

And in your main function, call the displayMatrix member like this:

newMatrix.displayMatrix( [B]numWords, inFile, wordsPtr[/B] );

You also have a parameter in the Matrix constructor which does nothing, so it may as well be removed.

Here is the corrected version of your code:

GeneExp.hpp

#include <string>
#include <iostream>

using namespace std;

class Matrix {
public:
  Matrix () {};
  ~Matrix() {};

  void displayMatrix(size_t numwords, std::ifstream &inFile, string *wordsPtr) {
    for (size_t i = 0; i < numwords; ++i) {
      inFile >> wordsPtr[i];
      cout << "Line #" << i << ": " << wordsPtr[i] << '\n';
    }
  }
};

test.cpp

#include <iostream>
#include <fstream>
#include <string>
#include "GeneExp.hpp"

using namespace std;

int main()
{
  //number of rows and cols
  string words[4][4];

  // Pointer to first element of words (acts as 1D array)
  string *wordsPtr = &words[0][0];

  //read in file
  ifstream inFile( "data.txt", ios::in );

  // Calculate number of words to retrieve
  size_t numWords = sizeof(words) / sizeof(string);

  Matrix newMatrix;

  newMatrix.displayMatrix( numWords, inFile, wordsPtr );

  /*for (size_t i = 0; i < numWords; ++i) {
	  inFile >> wordsPtr[i];
	  cout << "Line #" << i << ": " << wordsPtr[i] << '\n';
  }*/

  cout << "array pointer [1][1] is:" << words[1][1] << endl;
  cout << "array pointer [2][4] is:" << words[2][4] << endl;
  cout << "array pointer [3][3] is:" << words[3][3] << endl;

  return 0;			
}

Hope this helps.

Many thanks william....that's helped loads as i come to a halt. I can't beleive some of those errors were so obvious

I am trying to see if an array element contains a specific word and if it does then out put it and the location,

for (int i = 0; i < 4; ++i) {
	for (int j = 0; j < 4; j++) {
		if(words[i][j] == "0") {
			cout << "found in:" << words[i] << words[j] << endl;
		}	
	}
}

i get a syntax error pointing to ]

test.cpp(33) : error C2059: syntax error : ']'

I don't get that error, but i'm not entirely sure what it is you're trying do on this line.

cout << "found in:" << words[i] << words[j] << endl;

If you want to display the column and row of the word found, simply print the index of the word like this:

for (int i = 0; i < 4; ++i) {
  for (int j = 0; j < 4; j++) {
    if ( words[i][j] == "0" ) {
      cout << "0 found in:  x: " << i << "\ty: " << j << endl;
    }	
  }
}

Hope this helps.

Many thanks.....that is what i was trying to do....i put the [] in there when i shouldn't have. I'll remember that

I was trying to output this function into a 4 x 4 matrix using tabs but it's going through each line then doing the same number in a 4 x 4.

I have ot it to work if i put it in the main function but in the class function i can't get it to utput properly. I really appreciate all your help

Can you please help with this?

void displayMatrix(size_t numwords, std::ifstream &inFile, string *wordsPtr) {
    for (size_t i = 0; i < numwords; ++i) {
      inFile >> wordsPtr[i];
      cout << "Line #" << i << ": " << wordsPtr[i] << '\n';
	  
	  for (int a = 0; a < 4; a++) {
		for (int b = 0; b < 4; b++) {
			cout << wordsPtr[i] << '\t';
		}
		cout << "\n";
	}
    }

You need to move the part of the code which is displaying the grid out of the first for loop scope. Heres the simplest way for you to print the grid.

void displayMatrix(size_t numwords, std::ifstream &inFile, string *wordsPtr) {
  for (size_t i = 0; i < numwords; ++i) {
    inFile >> wordsPtr[i];
    cout << "Line #" << i << ": " << wordsPtr[i] << '\n';
  }
  for (int y = 0; y < 4; y++) {
    for (int x = 0; x < 4; x++) {
      cout << wordsPtr[y * 4 + x] << '\t';
    }
    cout << "\n";
  }
}

Hope this helps.

Thanks again...This has been doing my head in for ages.

In my code is there a way i can read each of the lines of the file and add whatever is between certain tags to an array?

I've been working on this all evening and just a couple more questions and i should be done

Here is a code snippet I made which should read a line of text and if the line contains <row> it skips the line. If the line contains </row> it escapes the loop otherwise it adds to the array. I would also use this on the previous code i got for adding the words to an array, so it skips tags like <word> and <word>

string rows[4];
string *rowsPtr = &rows[4];

string line;
string str1 = "<row>";
string str2 = "</row>";

size_t found;

found=line.find(str1);

while(getline(inFile, line)) {
	 if (found!=string::npos) continue;
	 
	 found=line.find(str2);
	 if (found!=string::npos) break;
	 else inFile >> rowsPtr[str];
	 cout << line << endl;
}

when i tried to run it i got nothing out. i don't know if it has anything to do with being in that class inside a function. I got no errors and i know the function was called properly but it displays nothing

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.