Hello! I am having some trouble with reading data for a list. If at the end of the file there is a new line character, this function reads the last set of data again, and then exits the loop. The addElem function works fine, I tested it separately. As there is almost impossible for me to generate a such text file without putting a new line character at the end of the file, i would like to know if there is a method to skip the new line character.

void aClass::readData(string filename)
{
	string name;
	string surname;
	string address;
	int type;
	float count;
	float cost;
	
	ifstream f;
	f.open(filename);
	aList.clear();
	id = 1;
	while (!f.eof())
	{
		f>>name>>surname>>address>>type>>count>>cost;
		this->addElem(name,surname,address,type,count,cost);
	}
	f.close();
}

It's probably better to read and write the entire object.
f.read( ( char* )aClassObject, sizeof( aClass ) );
f.write( ( char* )aClassObject, sizeof( aClass ) );

if 'aClass' is the object that holds:
name
surname
...

The way you are doing it can get tricky by having to put
'spacer tokens' ( as I put it ) at the end of each record.
By reading and writing the entire object, it is done cleanly.

I've found the structure of

while( !f.eof() )
if( !f.fail()
{
aClass* temp = new aClass();
f.read( ( char* )temp , sizeof( aClass ) );
}

...to have no problems

There is a known problem with .eof(). That's what that thread addresses and tells how to avoid it.

Also, the OP is not reading into a class, he/she's reading into strings etc. from a text file. .read() is meant for binary files, IIRC.

I've never had too many problems with eof(). Do the proper checking and you're in like flinn. Regardless what it is good for, I use it handily for binary and text files. What is OP? Is this some sort of class or something?

I've never had too many problems with eof(). Do the proper checking and you're in like flinn. Regardless what it is good for, I use it handily for binary and text files. What is OP? Is this some sort of class or something?

You've probably been taught correctly when eof() returns FALSE. I've found that most people use it without being taught correctly.

OP is shorthand for Original Poster, he who posts first.

And it's Flynn, by the way. A proper name. :icon_wink:

It's probably better to read and write the entire object.
f.read( ( char* )aClassObject, sizeof( aClass ) );
f.write( ( char* )aClassObject, sizeof( aClass ) );

Don't even think about it. This technique will not work if the object in question contains any members of type string, or vector, or any other type that manages any auxiliary memory.

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.