注册 登录
编程论坛 C++教室

文件问题

lovepiss 发布于 2008-03-17 19:37, 520 次点击
有两个文件text1.txt和text2.txt。两个文件中所存内容都是人名,并且每个名字都是一行一行存放。要求编写程序,把两个文件中名字相同的名字存到text3文件中。

这是我写的程序,但结果不正确,请帮忙修改写,谢谢。



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

int main()
{
    char str1[20],str2[20];
    ifstream file1,file2;
    ofstream file3;
    file1.open("text1.txt",ios_base::in|ios::binary);
    if(!file1)
    {
        cout<<"text1.txt cannot open"<<endl;
        return 0;
    }
    file2.open("text2.txt",ios::in|ios::binary);
    if(!file2)
    {
        cout<<"text2.txt cannot open"<<endl;
        return 0;
    }
    file3.open("text3.txt",ios::out|ios::binary|ios::app);
    if(!file3)
    {
        cout<<"text3.txt cannot open"<<endl;
        return 0;
    }
    while(!file1.eof())
    {
        file1.getline(str1,20);
        while(!file2.eof())
        {
            file2.getline(str2,20);
            if(strcmp(str1,str2)==0)
                file3.write(str1,sizeof(str1));//这个也有问题,把一写莫名其妙的的汉字也复制上去了,不知道怎么改
        }
               
        file2.seekg(0,ios::beg);//为什么指针不能回到文件开头?
    }
    file1.close();
    file2.close();
    file3.close();

    return 0;
}
1 回复
#2
newyj2008-03-17 21:23
这个用 批处理 更容易些
但是 效率就不行了
1