如何在 中输入记录的一个字段时搜索记录

How to search for a record when one field of the record in entered in c++

本文关键字:记录 一个 字段 搜索 输入      更新时间:2023-10-16

我试图在循环文件时将字符串输入与函数返回的字符串进行比较,如果输入等于文件中返回的字符串,它应该打印与输入字符串相关的详细信息。但是它一直给我错误消息invalid use of void expression...

#include <string>
#include <fstream>
#include <iostream>
using namespace std;
struct student { /* ... */ };
void search_course(string course)
{
    int check = 0;
    student st;
    
    ifstream file;
    file.open("student.dat", ios::binary | ios::out);
    
    if (!file) {         
        cout << "No Such file in Database...";      
        return; 
    }
    
    while (!file.eof() && check == 0) {
        file.read((char *) &st, sizeof(student));
        if (strcmp(st.return_prog(), course) == 0) {             
           st.showid_detail();
        }
    }
    
    file.close(); 
}
int main()
{
    string course = "physics";
    search_course(course);
}

showid_detail() 是类中的一个函数,它显示有关记录的信息,如下所示。 id, index, name, course, year, Hall return_prog()是一个void函数,用于输出学生的课程我期望代码显示所有那些做物理的学生,但它一直告诉我无效地使用空表达式......

return_prog(( 是一个 void 函数,用于输出学生的课程

所以有你的问题。

不会返回学生的课程,而是输出它。

您尝试在表达式中使用它strcmp(st.return_prog(), course)就好像它具有返回类型和值一样,但它没有。 strcmp不会神奇地检查操作数生成的控制台输出;它观察操作数的值。

我建议这样做。然后,如果您想要输出,您仍然可以在某个地方执行std::cout << st.return_prog()