向后显示文本

如何解决向后显示文本

我正在尝试逐行向后显示文本文件。我想用字符和动态分配来做到这一点。为此,我分配了一个二维动态数组。但问题是我读到的每一行都抹去了先例。 这是我的代码

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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?