ifstream garbage output.

closed account (DNwq5Di1)
Hello peepz, trying (for practice) to write a program that reads a list of names

and throw them out in a specific order... but that's really not the problem, right now ;)

My problem is that when i read the txt-file and prints it to the console, all the lines are there, and then there's a line of "garbage" at the end -.- i really don't know why. Any help?

Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <fstream>

using namespace std;


int main(int argc, char *argv[])
{
	
	char *cont;
	ifstream file;
	file.open("test.txt");
	
	file.seekg(0, ios::end);
	streamsize ln = file.tellg();

	cont = new char[(int)ln];

	file.seekg(0, ios::beg);
	file.read(cont, ln);

	cout << cont;
	return 0;
}


btw, don't mind the extra headers :p

Thanks in advance!
I have a feeling that a text file does not end with \0. Try adding it yourself. (allocate ln+1 chars and set cont[ln] = 0)
closed account (DNwq5Di1)
i added \0 to the end, which reduced it from
1
2
3
4
5
6
7
8
9
10
11
lolwut
this
is
several
lines
of
text
several
lines
repeating
══════════²²²²¦¦¦¦¦s¸¶9[♫


to
1
2
3
4
5
6
7
8
9
10
11
lolwut
this
is
several
lines
of
text
several
lines
repeating
═══════════


and ehmm, that line does not belong :P
no idea really. though you probably shouldn't be using read() for text anyway..
closed account (DNwq5Di1)
it seemed so simple!! xD

gotta find some other method then :/


else thanks for the help ^^
closed account (DNwq5Di1)
1
2
3
4
5
6
7
8
9
10
11
12
string line, cont;
	ifstream file;
	file.open("test.txt");
	
	if(file.is_open())
	{
		while(file.good())
		{
			getline(file, line);
			cont += line + (char)10;
		}
	}



was perfect :)

thanks, again, for the directions :P
Topic archived. No new replies allowed.