gpt4 book ai didi

c++ - 反转文件中的输入 (C++)

转载 作者:太空宇宙 更新时间:2023-11-04 11:55:44 24 4
gpt4 key购买 nike

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

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

编辑:抱歉,不得不离开。这是我到目前为止所拥有的。让它反转,只需要检查回文。将阅读回复。

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

最佳答案

我只是想知道比较 2 个列表是否适用于 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");

地点

file1.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 

关于c++ - 反转文件中的输入 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16201986/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com