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

时间:2013-07-02 15:48:15

标签: c++ multidimensional-array

我想从文本文件中读取一行到二维char数组,但没有换行符。

.txt示例:

TCAGC
GTAGA
AGCAG
ATGTC
ATGCA
ACAGA
CTCGA
GCGAC
CGAGC
GCTAG

...

到目前为止,我有:

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();
        }
    }

但是,我不知道如何忽略换行符。我希望对数组进行索引,以便我可以使用第一个索引访问序列,然后使用第二个索引访问该序列中的特定char;即store [0] [0]会给我'T',但我不希望store [0] [5]给我'\ n'。

另外,另外,存储[0] [6],我认为应该超出边界,因为BARCLGTH为5,返回'G',存储[0] [7]返回'T',存储[0] ] [8]返回'A'等。这些是下一行的字符。或者,存储[1] [0],存储[1] [1]和存储[1] [2]也会返回相同的值。为什么第一个设置返回值,它们不应该超出界限吗?

1 个答案:

答案 0 :(得分:2)

当您使用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();

在此之后,向量barcodes包含文件中的所有内容。不需要数组,也不需要计算行数。

由于向量和字符串都可以像数组一样编入索引,因此可以使用barcodes[2][0]之类的语法来获取第三个条目的第一个字符。