写一个程序来比较两个文件。如果两个文件是相同的,输出“相同”,否则,输出“不同”和第一个位置(从0开始)两个文件的不同。
答案应该写入文件。
The two input file names and one output file name are read from stdin.
每个文本只有一行
是c++的文件输入和输出哦~~
主要是我不会怎么读入两个文本,并比较。
谢谢~~
可以把结果也储存在一个文件里吗?
追答#include
#include
#include
#include
using namespace std;
int main(int argc, char **argv)
{
ifstream ifile1,ifile2;
ofstream ofile;
string str1, str2;
stringstream strOutput;
ifile1.open("1.txt", ios::in);
ifile2.open("2.txt", ios::in);
getline(ifile1,str1);
getline(ifile2, str2);
if (str1.compare(str2) == 0)
{
strOutput << string("1.txt里面的内容和2.txt里面的内容完全一样");
return 0;
}
else
{
strOutput << string("1.txt里面的内容和2.txt里面的内容不一样,不一样的起始位置在位置:");
string::size_type i = 0, str1Len = str1.size(), str2Len = str2.size();
while ((i < str1Len) && (i < str2Len))
{
if (str1[i] != str2[i])
{
break;
}
i++;
}
strOutput << (i + 1);
}
cout << strOutput.str() << endl;
ofile.open("3.txt", ios::out);
ofile << strOutput.str() << endl;
ifile1.close();
ifile2.close();
ofile.close();
return 0;
}