【问题标题】:Searching in binary file C++在二进制文件中搜索 C++
【发布时间】:2014-11-02 10:50:39
【问题描述】:
#include <iostream>
#include <fstream>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>

using namespace std;

class Student{
private:
    char name[40];
    char grade;
    float marks;
public:
    void getdata();
    void display();
    char* getname(){return name;}
    void search(fstream,char*);
};

void Student::getdata(){
    char ch;
    cin.get(ch);
    cout<<"Enter name : ";
    cin.getline(name,40);
    cout<<"Enter grade : ";
    cin>>grade;
    cout<<"Enter marks : ";
    cin>>marks;
    cout<<"\n";
}

void Student::display(){
    cout<<"Name : "<<name<<"\t";
    cout<<"Grade : "<<grade<<"\t";
    cout<<"Marks : "<<marks<<"\t"<<"\n";
}

void search(fstream fin,char* nm)/*initializing argument 1 of 'void search(std::fstream, char*)'*/{
    Student s;
    fin.open("stu.txt",ios::in|ios::binary);
    while(!fin){
        fin.read((char*)&s,sizeof(s));
        if(s.getname()==nm){
            cout<<"Record found !";
            s.display();
            break;
        }
    }
    fin.close();
}

int main(){
    system("cls");
    char nam[40];
    Student arts[3];
    fstream f;
    f.open("stu.txt",ios::in|ios::out|ios::binary);
    if(!f){
        cerr<<"Cannot open file !";
        return 1;
    }
    for(int i=0;i<3;i++){
        arts[i].getdata();
        f.write((char*)&arts[i],sizeof(arts[i]));
    }
    f.close();
    cout<<"Enter name to be searched for : ";
    cin.getline(nam,40);
    char* p = new char[40];
    p=nam;
    search(f,p);/*synthesized method 'std::basic_ios<char>::basic_ios(const std::basic_ios<char>&)' first required here*/
    getch();
    f.close();
    return 0;
}

上述程序首先创建一个文件“stu.txt”并将用户给定的输入写入该文件。 然后应该根据用户输入的名称搜索记录(使用 search() 函数)。调用 search() 并定义 search() 时出现错误。我已将编译器作为注释行抛出的错误放入其中。谁能解释那里出了什么问题?

【问题讨论】:

  • 您不能有fstream 参数,因为fstream 不能被复制。请改用fstream&amp;
  • 谢谢!这消除了错误!
  • 您能解释一下为什么 fstream& 有效吗?
  • 它通过引用传递流(通过引用查找传递)。

标签: c++ file class c++11 file-io


【解决方案1】:

fstream 不可复制,因此您必须将fstream 作为引用传递,或者在 c++11 中移动它。

如果你在调用search后访问f,最好通过引用传递。

更改您的函数以接受fstream 作为参考

void search(fstream& fin,char* nm)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-05
    • 1970-01-01
    • 1970-01-01
    • 2016-02-28
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    • 2015-06-19
    相关资源
    最近更新 更多