Jump to content
  • Advertisement
Sign in to follow this  
darenking

SOLVED! C++ reading a text file into strings

This topic is 4854 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hmm... I'm writing a routine that reads text from a .txt file, and it is working fine, but I have a small problem. It works something like this (simplified):
ifstream file("data.txt");

while ( ! file.eof() )
{
	file >> next;
	if ( next[0] == '1' )
	{
		//do stuff
		continue;
	}
//etc
}


In my text file I want to be able to put a slash '/' at the start of a line, like '//' in C. If I was reading line by line then it wouldn't be a problem, but I'm reading groups of characters separated by whitespace. How do I get it to skip to the next line? I want a simple way that doesn't involve rewriting the whole thing - for example I don't want to read whole lines generally as my datafiles aren't organised that way. I currently do it this way (below), which works, but three lines of code seems like a lot. Is there perhaps an ifstream method that does it?
	if ( next[0] == '/' )
	{
		char ch = ' ';
		while ( ch != '\n' )
		filenew.get(ch);
		continue;
	}


[Edited by - darenking on August 2, 2005 11:51:54 AM]

Share this post


Link to post
Share on other sites
Advertisement
std::string buffer;
std::getline( file, buffer, '\n' );


"buffer" contains the rest of the line up until '\n'.

Or, if you don't need the rest of the line,

file.ignore( x, '\n' );

Where x is the maximum amount of characters you want to skip before giving up. If you want to keep going until you reach the end of the file, use the value:

std::numeric_limits<std::streamsize>::max

Share this post


Link to post
Share on other sites
Excellent, have now reduced from this:


if ( next[0] == '/' )
{
char ch = ' ';
while ( ch != '\n' )
file.get(ch);
continue;
}



to this:


if ( next[0] == '/' )
{
getline( file, next, '\n' );
continue;
}



Thanks gang!



Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!