Hi, I'm trying to do a program where I have to input 4 lines of text from a txt file, char by char into 4 seperate arrays (1 for each line). I have this

ifstream input("c:\\p2input.txt");
	for (int z = 0; z < 250; z++)
	{
		while (!input.eof())
		{
			input.getline(f, 250);
		}
	}

	for (int c = 0; c < 250; c++)
	{
		cout <<f[c];
	}

But it outputs the 4th line of text, followed by the second half of the third and then gibberish. Also, how do you get it to do just the second line, or just the third line? I'm using size 250 arrays because the lines cannot be more than 250 chars. Thanks.

Would you not be better of using strings in the modern world of C++ or is this an assignment?

Sorry to ask this just don't wanted to go into this method if we can just use strings :)

Chris

Would you not be better of using strings in the modern world of C++ or is this an assignment?

Sorry to ask this just don't wanted to go into this method if we can just use strings :)

Chris

Its for an assignment

OK.
Your array should be initialized to null terminating chars and when printing out would should print all of the characters upto the first null terminator rather than all 250.

So you will need to check if the array position is equal to '\0'

Chris

You are outputting the full array. Your output routine should stop when it encounter the NULL terminator of the fourth string.

Rather than loop through the array, why not just cout << f; Going further, your assignment says to use separate arrays for each input string. You have only one, which is why you see remnants of the first three when displaying the fourth. You need to allocate a 2D array of char.

To expand on what vmanes said, create a 2D array, something like inputbuffer[4][250] (4 lines, 250 chars each).
Reading each character, load the characters in the array.
When you reach the end of one line from the file, add a \0 character and point to the beginning of the next buffer line.
When done, you can output each line using puts() .

Try this

ifstream input("test.txt");
	char f1 [250], f2 [250];
		while (!input.eof())
		{
			
			input.getline(&f1[0],250);
			input.getline(&f2[0],250);
			
		}
		cout <<f1 << endl << f2 << endl;
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.