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

时间:2015-08-28 23:12:28

标签: c++ reverse

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

我按正常顺序制作了代码(并且确实有效),我只需要让程序反向显示顺序。

该文件只是一个包含数字的文本文件。

这就是我所拥有的:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {

ifstream file("numbers.dat");
string content;

while(file >> content) {
cout << content << ' ';
}
return 0;
}

1 个答案:

答案 0 :(得分:3)

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

#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;
}