Sign in to follow this  
darenking

SOLVED! C++ reading a text file into strings

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this