从文件反转输入(c++)
Reversing an input from a file (C++)
我正在创建一个非常基本的程序,它从文本文件中读取一列数字,以相反的顺序打印它们,然后声明该顺序是否与原始顺序相同(如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容器上工作)
相关文章:
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 检查输入是否不是整数或数字
- 正在尝试了解输入验证循环
- 读取文件并输入到矢量中
- C++如何通过用户输入删除列表元素
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 用户定义函数中的指针和输入
- 如何在C++中检查2D数组中负值的输入验证
- 如何只允许用户输入正整数
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 输入中的字符串数未知(以字母表示)
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 在一个模板函数中,若输入的类型是enum类,我该如何使用std::underlying_type