int main() {
int len;
cout<<"Enter the size of dynamic array you want: ";
cin>>len;
int file_len;
int *new_num;
ifstream in("test.txt");
in.seekg(0, ios::end);
file_len = in.tellg();
in.close();
if(file_len>len)
{
int times= file_len/len;
for(int i=0; i<times; i++)
{
ifstream in("test.txt");
if(i==0)
{
char *n_ch = new char[len];
in.seekg(0, ios::cur);
in.read(n_ch, len);
cout<<n_ch<<"\'";
delete n_ch;
} else {
char *n_ch = new char[len];
in.seekg(i*len, ios::cur);
in.read(n_ch, len);
cout<<",,"<<n_ch<<"..";
delete n_ch;
}
}
in.close();
}
return 0;
}
我要做的是得到第n个到第(n+len)个字母并将它们放入一个数组中,然后打印它们。
现在我得到了这个结果,test.txt的内容是:
ABCDEABCDE
qwerty poiuy
zxcvb
mnbhhg
ooooo
我找不到我得到额外字母的原因,我猜那是下一个字母的第一个字母。 有办法解决这个问题吗?
你读的是C字符串。 C字符串以null结尾,也就是说,它们需要在结尾处有一个null字符来指示字符串的长度。 你的代码可不这么做。 试试这个
char *n_ch = new char[len + 1]; // one extra for the null terminator
in.seekg(0, ios::cur);
in.read(n_ch, len);
n_ch[len] = '\0'; // add the null terminator
cout<<n_ch<<"\'";
delete n_ch;
在in.read(n_ch,len)
之后,您需要使用gcount()
查看实际读取了多少字符。 假设您的文件有37个字符,并且您正在以10个字符为块进行读取:最后一次读取将只返回7个字符,并且您希望确保只尝试将7个字符写入输出(可以使用cout.write(n_ch,gcount());
)。