访问次数:

基于顺序存储结构的图书信息表的新图书的入库 | Wenji's blog
头部背景图片
WenJi's blog |
WenJi's blog |

基于顺序存储结构的图书信息表的新图书的入库

描述
定义一个包含图书信息(书号、书名、价格)的顺序表,读入相应的图书数据来完成图书信息表的创建,然后根据指定的待入库的新图书的位置和信息,将新图书插入到图书表中指定的位置上,最后输出新图书入库后所有图书的信息。

输入
总计n+3行。首先输入n+1行,其中,第一行是图书数目n,后n行是n本图书的信息(书号、书名、价格),每本图书信息占一行,书号、书名、价格用空格分隔,价格之后没有空格。其中书号和书名为字符串类型,价格为浮点数类型。之后输入第n+2行,内容仅为一个整数,代表待入库的新图书的位置序号。最后输入第n+3行,内容为新图书的信息,书号、书名、价格用空格分隔。

输出
若插入成功:

输出新图书入库后所有图书的信息(书号、书名、价格),总计n+1行,每行是一本图书的信息,书号、书名、价格用空格分隔。其中价格输出保留两位小数。

若插入失败:

只输出以下提示:抱歉,入库位置非法!

样例输入1 复制
7
9787302257646 Data-Structure 35.00
9787302164340 Operating-System 50.00
9787302219972 Software-Engineer 32.00
9787302203513 Database-Principles 36.00
9787810827430 Discrete-Mathematics 36.00
9787302257800 Data-Structure 62.00
9787811234923 Compiler-Principles 62.00
2
9787822234110 The-C-Programming-Language 38.00
样例输出1
9787302257646 Data-Structure 35.00
9787822234110 The-C-Programming-Language 38.00
9787302164340 Operating-System 50.00
9787302219972 Software-Engineer 32.00
9787302203513 Database-Principles 36.00
9787810827430 Discrete-Mathematics 36.00
9787302257800 Data-Structure 62.00
9787811234923 Compiler-Principles 62.00

这道题最开始wa的时候,我以为是由于我没用英文,
最后发现是由于没注意到插入的次序,也就是先后移之后
在插入。而我先插入之后再后移,就会造成数据出现重复。

正确代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include<cstdio>
#include<cstring>
#include<iostream>
#include<string>
#include<algorithm>
#include<cmath>
#define MAXSIZE 1000
#define OK 1
#define ERROR 0
using namespace std;
typedef struct
{
char no[20];
char name[50];
float price;
}Book;
typedef struct
{
Book *elem;
int length;
}SqList;
SqList L;
int N;
bool IninList(SqList &L)
{
L.elem = new Book[MAXSIZE];
if (!L.elem) exit(OVERFLOW);
L.length = 0;
return OK;
}
int main()
{
cin>>N;
IninList(L);
for(int i=0;i<N;i++)
{
scanf("%s%s%f", L.elem[i].no, L.elem[i].name, &L.elem[i].price);
L.length++;
}
int position;
Book book;
cin>>position;
scanf("%s%s%f", book.no, book.name, &book.price);
if(position<1||position>(L.length+1))
cout<<"Sorry, the storage location is illegal!"<<endl;
else
{
L.length++;
for(int i=L.length-1;i>=position;i--)
{
L.elem[i]=L.elem[i-1];
}
L.elem[position-1]=book;
for(int j=0;j<L.length;j++)
printf("%s %s %.2f\n",L.elem[j].no,L.elem[j].name,L.elem[j].price);}
delete[] L.elem;
return 0;
}