主函数里怎么写?如何将图书信息写入顺序表里


#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
typedef int ElemType;
#define MAXSIZE 100
struct Book{
    string id;
    string name;
    double price;
};
typedef struct{
    Book *elem;
    int length;
}SqList;
Status InitList_Sq(SqList&L)//构造一个空的顺序表L
{
L.elem=new Book[MAXSIZE];
if(!L.elem) exit(OVERFLOW);
L.length=0;
return OK; 
 }
 Status GetElem(SqList L,int i,Book &e)//取值
 {if(i<1||i>L.length)
 return ERROR;
 e=L.elem[i-1] ;
 return OK;
  }
  int LocateElem_Sq(SqList L,double e)//查找
  {
  for(int i=0;i<L.length;i++)
  if(L.elem[i].price==e ) return i+1;
  return 0;
}
Status Listlnsert_Sq(SqList&L,int i,Book e)//插入
{if((i<1)||(i>L.length+1)) return ERROR;
if(L.length==MAXSIZE) return ERROR;
for(int j=L.length-1;j>=i-1;j--)
L.elem[j+1]=L.elem[j];
L.elem[i-1]=e;
++L.length;
return OK;
 }
 Status ListDelete_Sq(SqList&L,int i)//删除 
 {if((i<1)||(i>L.length))
 return ERROR;
for(int j=i;j<=L.length-1;j++)
L.elem[j-1]=L.elem[j];
--L.length;
return OK;
}
int main()

img

引用 皆我百晓生 小程序回复内容作答:

{
    SqList L;
    InitList_Sq(L); // 初始化顺序表
    Book b;
    ifstream file("book.txt"); // 打开文件
    while(file >> b.id >> b.name >> b.price) // 依次读取文件中的书籍信息
    {
        Listlnsert_Sq(L, L.length + 1, b); // 将书籍信息插入顺序表中
    }
    file.close(); // 关闭文件

    // 打印顺序表中的书籍信息
    for(int i = 1; i <= L.length; i++)
    {
        GetElem(L, i, b);
        cout << "编号:" << b.id << " 书名:" << b.name << " 价格:" << fixed << setprecision(2) << b.price << endl;
    }

    return 0;
}

【以下回答由 GPT 生成】

主函数可以通过以下步骤调用这些函数,将图书信息写入顺序表中:

  1. 引入头文件和命名空间: c++ #include <iostream> #include <string> #include <iomanip> #include <fstream> #include "yourfile.h" // 如果这些函数定义在另一个文件中,需要包含头文件 using namespace std;
  2. 如果这些函数定义在另一个文件中,需要在主函数中引入头文件,并将头文件中的函数实现包含进来。

  3. 声明主函数: c++ int main() { // 主函数代码 // ... return 0; }

  4. 初始化顺序表: c++ SqList L; InitList_Sq(L);

  5. 创建图书对象并赋值: ```c++ Book book1; book1.id = "1001"; book1.name = "Harry Potter"; book1.price = 29.99;

Book book2; book2.id = "1002"; book2.name = "Lord of the Rings"; book2.price = 39.99; ```

  1. 将图书信息插入顺序表中: c++ Listlnsert_Sq(L, 1, book1); // 在第一个位置插入book1 Listlnsert_Sq(L, 2, book2); // 在第二个位置插入book2

完整的代码示例:

#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
#include "yourfile.h" // 如果这些函数定义在另一个文件中,需要包含头文件
using namespace std;

int main() {
    SqList L;
    InitList_Sq(L);

    Book book1;
    book1.id = "1001";
    book1.name = "Harry Potter";
    book1.price = 29.99;

    Book book2;
    book2.id = "1002";
    book2.name = "Lord of the Rings";
    book2.price = 39.99;

    Listlnsert_Sq(L, 1, book1);
    Listlnsert_Sq(L, 2, book2);

    return 0;
}

请注意,这只是一个简单的示例,在实际的应用中,你可能需要从文件中读取图书信息,而不是硬编码在代码中。另外,还需要释放内存,关闭文件等操作。



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^