从文件反转输入(c++)

Reversing an input from a file (C++)

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

我正在创建一个非常基本的程序,它从文本文件中读取一列数字,以相反的顺序打印它们,然后声明该顺序是否与原始顺序相同(如palendrome)。

到目前为止,我的程序能够以相反的顺序打印,但我不确定如何检测它是否与原始文件相同。任何帮助都将是非常感激的:)

编辑:对不起,我不得不离开。这是我目前所知道的。把它倒过来了,只需要检查一下回文。将阅读回复。
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
const int ARRYLENGTH=20;
int contnums[ARRYLENGTH];
int contents;

ifstream myFile("problem3.txt");
if(! myFile )
{
cout << "File cannot be found";
exit(EXIT_FAILURE);
}
while(!myFile.eof())
{
myFile>>contents;
    for(int i=0;i<ARRYLENGTH;i++)
    {
    myFile >> contnums[i];
    }
}
cout<<contents<<" ";
for (int i = 1; i < ARRYLENGTH; i++)
{
bool same = false;
for (int j = 0; j < i && (same == false); j++){
if (contnums[i] == contnums[j]) 
same = true;
}
if (!same) {
cout<< contnums[i] << " ";
}
}
cout << "n";
system("pause");
myFile.close();
}

我只是想知道比较两个列表是否会在std库中工作。它工作:-)

#include <list>
#include <fstream>
using std::list;
using std::ifstream;
bool foo(const char * fn)
{
    list<int> orig;
    list<int> rev;
    ifstream ifs(fn,std::ifstream::in);
    while( ifs.good() && !ifs.eof() )
    {
        int num =0;
        ifs >> num;
        orig.push_back(num);
        rev.push_front(num);
    }
    bool equal = (orig == rev);
    return equal;
}
static bool test1 = foo("file1.txt");
static bool test2 = foo("file2.txt");

,

中包含

1 2 3 4 5 6 7 8 9 0 9 8 7 6 5 4 3 2 1 8

和file2.txt包含

1 2 3 4 5 6 7 8 9 0 9 8 7 6 5 4 3 2 1 

尝试从头到尾迭代,并将值与迭代器的值从头到尾进行比较。

如果你知道你有多少项,可以简单地做到:

for(int i = 0; i < count/2; ++i) { //count/2 becouse you only have to check half
   if(array[i] != array[count-i-1]) { /*not palindrome */ }
}
//palindrome
最简单的方法,但是我更喜欢评论1中的@Dave的方法,因为它很好地使用了STL和迭代器。(只要你在STL容器上工作)