如何解决向后显示文本
我正在尝试逐行向后显示文本文件。我想用字符和动态分配来做到这一点。为此,我分配了一个二维动态数组。但问题是我读到的每一行都抹去了先例。 这是我的代码:
int main()
{
char path[256]; string name;
cout << "Enter path:" << endl; cin >> path;
ifstream file(path);
if (!file) { cout << "ERROR" << endl; return -1; }
char** sentence = new char* [100];
for (int i = 0; i < 100; i++)
*sentence = new char[120];
char line[120];
int index = 0;
while(!file.eof())
{
file.getline(line,120);
sentence[index++] = line; //Erase precedent line
}
for (int i = 0; i < index; i++)
cout << sentence[i] << endl;
return 0;
}
解决方法
我不确定是否有更有效的方法来解决这个问题。
void readFile(char *fileName){
char c;
std::ifstream myFile(fileName,std::ios::ate);
std::streampos size = myFile.tellg();
for(int i=1;i<=size;i++){
myFile.seekg(-i,std::ios::end);
myFile.get(c);
printf("%c\n",c);
}
}
,
这不是你想的那样:
sentence[index++] = line; //Erase precedent line
这会将 line
的地址分配给 sentence[index]
。这不是您想要的,因为在循环结束时 sentence
中的所有值都指向 line
(因此泄漏了所有动态分配的内存)。
要完成这项工作,您需要将字符串复制到目的地。
std::copy(line,strlen(line),sentence[index++]);
然而:这可能不是最好的解决方案。您应该使用 C++ 对象而不是低级 C 字符串。 C++ 对象可以为您解决这个问题,无需手动复制或动态分配。
快速提示是新的/删除的,或者对初学者来说可能是个坏主意。如果您的代码包含它们,那么您就做错了(或者编写了 C 并且碰巧使用了 C++ 编译器来编译代码)。
int main()
{
/*
Replace this with std::vector<std::string>
char** sentence = new char* [100];
for (int i = 0; i < 100; i++)
*sentence = new char[120];
*/
// Great thing about vectors is that they will resize.
std::vector<std::string> sentence;
std::string line;
// Use the read operation as the condition of the loop
// If you fail to read then you should not add it to sentence.
// Note `line` will dynamically re-size for any size of line.
while(std::getline(file,line))
{
sentence.push_back(line);
}
// You can finish it.
// Iterate over the `sentence` backwards and print them out.
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。