简体   繁体   English

C ++从文本文件读取到const char数组

[英]C++ Reading from a text file into a const char array

I want to read in lines from a text file into a 2-d char array but without the newline character. 我想从文本文件中读取一行到二维char数组但没有换行符。

Example of .txt: .txt示例:

TCAGC
GTAGA
AGCAG
ATGTC
ATGCA
ACAGA
CTCGA
GCGAC
CGAGC
GCTAG

... ...

So far, I have: 到目前为止,我有:

ifstream infile;
infile.open("../barcode information.txt");
string samp;
getline(infile,samp,',');
BARCLGTH = samp.length();
NUMSUBJ=1;
while(!infile.eof())
{
getline(infile,samp,',');
NUMSUBJ++;
}
infile.close();  //I read the file the first time to determine how many sequences
                 //there are in total and the length of each sequence to determine
                 //the dimensions of my array. Not sure if there is a better way?
ifstream file2;
file2.open("../barcode information.txt");
char store[NUMSUBJ][BARCLGTH+1];

    for(int i=0;i<NUMSUBJ;i++)
    {
        for(int j=0;j<BARCLGTH+1;j++)
        {
        store[i][j] = file2.get();
        }
    }

However, I do not know how to ignore the newline character. 但是,我不知道如何忽略换行符。 I want the array to be indexed so that I can access a sequence with the first index and then a specific char within that sequence with the second index; 我希望对数组进行索引,以便我可以使用第一个索引访问序列,然后使用第二个索引访问该序列中的特定char; ie store[0][0] would give me 'T', but I do not want store[0][5] to give me '\\n'. 即store [0] [0]会给我'T',但我不希望store [0] [5]给我'\\ n'。

Also, as an aside, store[0][6], which I think should be out of bounds since BARCLGTH is 5, returns 'G',store[0][7] returns 'T',store[0][8] returns 'A', etc. These are the chars from the next line. 另外,另外,存储[0] [6],我认为应该超出边界,因为BARCLGTH为5,返回'G',存储[0] [7]返回'T',存储[0] [8] ]返回'A'等。这些是下一行的字符。 Alternatively, store[1][0],store[1][1], and store[1][2] also return the same values. 或者,存储[1] [0],存储[1] [1]和存储[1] [2]也会返回相同的值。 Why does the first set return values, shouldn't they be out of bounds? 为什么第一个设置返回值,它们不应该超出界限吗?

As you're coding in C++, you could do like this instead: 当您使用C ++编写代码时,您可以这样做:

std::vector<std::string> barcodes;

std::ifstream infile("../barcode information.txt");

std::string line;
while (std::getline(infile, line))
    barcodes.push_back(line);

infile.close();

After this the vector barcodes contains all the contents from the file. 在此之后,矢量barcodes包含文件中的所有内容。 No need for arrays, and no need to count the number of lines. 不需要数组,也不需要计算行数。

And as both vectors and strings can be indexed like arrays, you can use syntax such as barcodes[2][0] to get the first character of the third entry. 由于矢量和字符串都可以像数组一样索引,因此您可以使用barcodes[2][0]等语法来获取第三个条目的第一个字符。

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

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