reading integers from files

Whether you're a newbie or an experienced programmer, any questions, help, or just talk of any language will be welcomed here.

Moderator: Coders of Rage

Post Reply
polyneem
Chaos Rift Newbie
Chaos Rift Newbie
Posts: 11
Joined: Tue May 11, 2010 7:23 pm

reading integers from files

Post 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 ;

}
User avatar
avansc
Respected Programmer
Respected Programmer
Posts: 1708
Joined: Sun Nov 02, 2008 6:29 pm

Re: reading integers from files

Post by avansc »

Some person, "I have a black belt in karate"
Dad, "Yea well I have a fan belt in street fighting"
User avatar
Ginto8
ES Beta Backer
ES Beta Backer
Posts: 1064
Joined: Tue Jan 06, 2009 4:12 pm
Programming Language of Choice: C/C++, Java

Re: reading integers from files

Post 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.
Quit procrastinating and make something awesome.
Ducky wrote:Give a man some wood, he'll be warm for the night. Put him on fire and he'll be warm for the rest of his life.
User avatar
avansc
Respected Programmer
Respected Programmer
Posts: 1708
Joined: Sun Nov 02, 2008 6:29 pm

Re: reading integers from files

Post by avansc »

whoops. yes.
Some person, "I have a black belt in karate"
Dad, "Yea well I have a fan belt in street fighting"
polyneem
Chaos Rift Newbie
Chaos Rift Newbie
Posts: 11
Joined: Tue May 11, 2010 7:23 pm

Re: reading integers from files

Post by polyneem »

thank you all for your help, I have it working now
Post Reply