I put together this little example to test my sanity, and it failed!

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

using namespace std;

/* Example.txt
23
test
4.5
*/

int main(int argc, char *argv[])
{
	string Filename = argv[1];
	cout << "Filename: " << Filename << endl;

	int Integer;
	string String;	
	double Double;

	ifstream fin(Filename.c_str());

	string line;
	stringstream linestream;
		
	getline(fin, line);
	linestream.str("");
	linestream << line;
	linestream >> Integer;	

	getline(fin, line);
	linestream.str("");
	linestream << line;
	linestream >> String;

	getline(fin, line);
	linestream.str("");
	linestream << line;
	linestream >> Double;

	fin.close();

	cout << "Integer: " << Integer << endl;
	cout << "String: " << String << endl;
	cout << "Double: " << Double << endl;
	
	return 0;
}

The output is

Filename: Example.txt
Integer: 65535
String: 
Double: 4.86439e-270

Can anyone spot the stupid bug?

Thanks,

Dave

A stringstream is still a stream. When you read to end-of-file, you need to clear the state before you can do anything substantial with the stream again:

linestream.clear();
linestream << line;
...

That's what I thought I was doing with

linestream.str("");

But I changed all of those to

linestream.clear()

And I get the same garbage results.

Dave

I get correct results with the following code. The only changes were the ones you claim to have made:

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

using namespace std;

/* Example.txt
23
test
4.5
*/

int main(int argc, char *argv[])
{
	string Filename = argv[1];
	cout << "Filename: " << Filename << endl;

	int Integer;
	string String;	
	double Double;

	ifstream fin(Filename.c_str());

	string line;
	stringstream linestream;
		
	getline(fin, line);
	linestream << line;
	linestream >> Integer;	

	getline(fin, line);
	linestream.clear();
	linestream << line;
	linestream >> String;

	getline(fin, line);
	linestream.clear();
	linestream << line;
	linestream >> Double;

	fin.close();

	cout << "Integer: " << Integer << endl;
	cout << "String: " << String << endl;
	cout << "Double: " << Double << endl;
	
	return 0;
}

Just tested it with the changes mentioned, and it works for me too.

haha OH NO! The file was in the wrong directory... it works now.

I didn't gaurd it with

if(fin == NULL)

because it was just a toy example... but clearly I should have!

Sorry for the silly mistake.

Dave

I'd think about how to check if a file is really open :)

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.