Page 1 of 1

reading integers from files

Posted: Sat Jun 12, 2010 4:53 pm
by polyneem
I'm pretty new to the whole c++ scene, and am wondering how to go about reading integers from a text file. I tried the following code, it works fine with chars but not with ints.

Code: Select all

#include <fstream>

#include <iostream>

using namespace std ;





int main()

{

	int letter ;

	int i ;

	//string line ;



	ifstream reader( "poem.txt" ) ;



	if( ! reader )

	{

		cout << "Error opening input file" << endl ;

		return -1 ;

	}

	else

	for( i = 0; ! reader.eof() ; i++ )

	{

		reader.get( letter ) ;

		cout << letter ;


	}



	reader.close() ;

	

	cout << "Iterations: " << i << endl ;

	

	return 0 ;

}

Re: reading integers from files

Posted: Sat Jun 12, 2010 5:04 pm
by avansc

Re: reading integers from files

Posted: Sat Jun 12, 2010 6:44 pm
by Ginto8
He'd want fscanf rather than fprintf: He also might want these articles: I'd recommend the first one, but if for some strange reason you prefer iostream-type access, use the second one.

Re: reading integers from files

Posted: Sat Jun 12, 2010 6:56 pm
by avansc
whoops. yes.

Re: reading integers from files

Posted: Sat Jun 12, 2010 7:19 pm
by polyneem
thank you all for your help, I have it working now