Link to home
Start Free TrialLog in
Avatar of DarkNova
DarkNova

asked on

How do you read a line from a file to a string?

I'm trying to read a file with a loop and put each line in a cstring. Here's my code:

string messageBuffer;
while(!messageFile.eof())
 { messageBuffer = "";
   getline(messageFile, messageBuffer);
   if(messageBuffer == "")
    { messageBuffer = "\n"; }
   sendToServer(s, messageBuffer, NO);
 }
This works fine for most lines, and doesn't save the \n to the cstring, just like it's supposed to, but when it gets to a blank line, where the \n is the only thing on the line, it totally skips it and goes on to the next line. If my file's like this:

Test 1

Test 2

-and I read it with this loop, it ends up being like:

Test 1
Test 2

-I tried using the cstring function:
messageBuffer.read_line(messageFile);
instead of:
getline(messageFile, messageBuffer);

-it gives the exact same results, which makes me think that the cstring class won't let it return just nothing, which what it should do if a \n is stripped off a line w/ just \n.

I tried this exact same loop using char messageBuffer[100] and char functions instead, and it works perfectly.

Also, tabs seem to be stripped out when they're saved to a string as well. Does anyone know what's wrong? Thanks.
Avatar of DarkNova
DarkNova

ASKER

Edited text of question
I don't have the source code to read_line handy at the moment, but it looks like it is behaving like a stream >> operator to a string which eats whitespace.

use fscanf or a combo of fgets and sscanf to do formatted input reading.
ASKER CERTIFIED SOLUTION
Avatar of mann061997
mann061997

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial