如何在c++中反转和显示文本文件中的值

How to reverse and display the values in a text file in C++?

本文关键字:文本 显示 文件 c++      更新时间:2023-10-16

我的目标是能够以反向顺序读取/显示文件中的数字。

我编写了以正常顺序执行的代码(并且它确实有效),我只需要让程序以相反的顺序显示

文件只是一个文本文件,里面有数字。

我有:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream file("numbers.dat");
string content;
while(file >> content) {
cout << content << ' ';
}
return 0;
}

将文件中的数字存储在容器中,从后往前打印。

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
int main() 
{
    std::ifstream file("numbers.dat");
    std::string content;
    std::vector<std::string> numbers;
    while(file >> content) 
        numbers.push_back(content);
    for(int i = numbers.size() - 1; i >= 0; i--)
        std::cout << numbers[i] << ' ';
    std::cout << std::endl;
    return 0;
}