简体   繁体   中英

C++ Reading multiple lines from a file to a single string

I have an input file of dna.txt which looks like what is below. I'm trying to read all of the characters to a single string and I'm not allowed to use a character array. How would I go about doing this.

cggccgattgtattctgtatagaaaaacac
atacagatggattttaactagagc
aagtcgcaataaccagcgagtattaca
cctcgaccaaatcctcgaattctc

Try the following:

std::string dna;
std::string text_read;
while (getline(input_file, text_read))
{
    dna += text_read;
}

In the above loop, each line is read into a separate variable.
After the line is read, then it is appended to the DNA string.

Edit 1: Example working program:
Note: on some platforms, there may be a \\r' in the buffer which causes portions to be overwritten when displayed.

#include <iostream>
#include <fstream>
#include <string>

int main()
{
    std::ifstream input_file("./data.txt");
    std::string dna;
    std::string text_read;
    while (std::getline(input_file, text_read))
    {
        const std::string::size_type position = text_read.find('\r');
        if (position != std::string::npos)
        {
            text_read.erase(position);
        }
        dna += text_read;
    }
    std::cout << "As one long string:\n"
              << dna;
    return 0;
}

Output:

$ ./dna.exe
As one long string:
cggccgattgtattctgtatagaaaaacacatacagatggattttaactagagcaagtcgcaataaccagcgagtattacacctcgaccaaatcctcgaattctc

The file "data.txt":

cggccgattgtattctgtatagaaaaacac
atacagatggattttaactagagc
aagtcgcaataaccagcgagtattaca
cctcgaccaaatcctcgaattctc

The program compiled using g++ version 5.3.0 on Cygwin terminal.

The issue was found by using the gdb debugger.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM