Hi,
how can i save the text from a file in a 2d array?

For example the file will be like:
ebjevjhb tgbvtrjk trjgbj
tgrrktgtr kgtrl tkltrg t
feg ergfern gn sdcx xssw

And i want to save this in a char 2d array like:
char str[3][100]

so

str[0]="ebjevjhb tgbvtrjk trjgbj"
str[1]="tgrrktgtr kgtrl tkltrg t"
str[2]="feg ergfern gn sdcx xssw"

Thanks in advance.

Recommended Answers

All 4 Replies

Do you know how long each line is and also how long the file is overall? If not, dynamic allocation will be required and the algorithm changes dramatically.

For simplicity, and if allowed by your instructor, you may want to consider using a vector<string> instead of a 2-d array.

You will want to include <fstream> and use ifstream's getline() function.

I tried something like:

#include <fstream>
#include <iostream>
#include <string.h>
using namespace std;

int main()
{
	ifstream in("input.in");
	ofstream out("output.out");
	char str[20000][80];
	
	int i=0;
        for (;;){
		in.getline(str[i], 80,'\n');
		i++;
		if (in.eof()) break;
	}
	int m=i;
	
	
	for (int i=0;i<m;i++){
		for (int j=0;j<strlen(str[i]);j++){
			out << str[j];
			cout << str[j];
		}
		out << endl;
		cout << endl;
	}

	
	return 0;
}

but it isn't correct.
Can you see any mistake in my code?

Fbody: i know the max size.

line 13: That loop can be written better to avoid the last line problem. The default behavior of getline is to read until either 80 characters have been read of '\n' is reached, so there is no need to specify a third parameter to the function.

while( in.getline(str[i], 80) ) 
{
   ++i;
}

line 21: variable i has already been declared on line 12 so there is no reason to declare another variable with the same name on this line. Reuse variables whenever possible.

line 23: you need to add '\n' to the end of the string so that they all don't run together.

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.