简体   繁体   English

C++ 从文件中读取多行到单个字符串

[英]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.我有一个 dna.txt 的输入文件,如下所示。 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.读取该行后,将其附加到 DNA 字符串中。

Edit 1: Example working program:编辑 1:示例工作程序:
Note: on some platforms, there may be a \\r' in the buffer which causes portions to be overwritten when displayed.注意:在某些平台上,缓冲区中可能有一个\\r'会导致部分在显示时被覆盖。

#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":文件“data.txt”:

cggccgattgtattctgtatagaaaaacac
atacagatggattttaactagagc
aagtcgcaataaccagcgagtattaca
cctcgaccaaatcctcgaattctc

The program compiled using g++ version 5.3.0 on Cygwin terminal.在 Cygwin 终端上使用g++ 5.3.0 版编译的程序。

The issue was found by using the gdb debugger.该问题是通过使用gdb调试器发现的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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