[英]C++ Reading from a text file into a const char 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]也会返回相同的值。 为什么第一个设置返回值,它们不应该超出界限吗?
当您使用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]
等语法来获取第三个条目的第一个字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.