Hello!

I am currently attempting to read all the lines from a text file, and append them to one long string.
At the moment, it seems that the line that is read in keeps overriding the string, instead of appending it.

I think it has something to do with the newline character within the textfile, but I'm not 100% sure how that is affecting it. Just wondering how I would append the strings to one long one.

Any help would be appreciated,
Thanks!

int main(){

    string  line,
            fullLine;

    ifstream in("data.txt");
    if(!in){
        cerr << "Unable to open file" << endl;
        return 1;
    }

    while(getline(in,line)){
        fullLine += line;
    }
    cout << fullLine << endl;
}

The text file (data.txt) contains :

rachel
hello
goodbye

and the output is:

goodbye

Looks find to me:

/*
 * Output:
 * rachelhellogoodbye
 */

Try with the append function from the string class:

while(getline(in,line)){
        fullLine.append(line);
    }

Or with insert:

    while(getline(in,line)){
        for (size_t i=0;i<line.size();i++)
            fullLine.insert(fullLine.end(), line[i]);
    }

Take a look at the getline method. If you don't provide any delimitter, the new line character will be the delimitter, so there shouldn't be any problems caused by the '\n' character.
Links:
getline
Append.
Insert.

It all looks fine to me too, just a few things to clean up:
*Close the file when you're finished with it - in.close();
*Pause execution to read the string ( cin.get() or similar) and then return 0;

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.