CRUD(添加/查看/编辑/删除/查看所有记录)

CRUD (Add/View/Edit/Delete/ViewAll Record)

本文关键字:记录 删除 添加 查看 编辑 CRUD      更新时间:2023-10-16

我在字符串输入时遇到问题,每当我输入字符串时,程序都会停止运行,如果可能的话,请在记录上修复我的语句,因为它们似乎不能很好地工作。另外,如何删除字符串?我试图在这里用"无"代替它作为样本。提前谢谢你!

这是我的代码:

#include <iostream>
using namespace std;
int main(){
//Initializing
char choice;
int i, j, record=0, totalrecord;
int id[record];
string name[record];
double price[record];
bool back=true;
string none;

//Menu
while(back=true){   
cout<<"*******************************"<<endl;
cout<<"[A] Add Record"<<endl;
cout<<"[V] View Record"<<endl;
cout<<"[E] Edit Record"<<endl;
cout<<"[D] Delete Record"<<endl;
cout<<"[L] View All Record"<<endl;
cout<<"Enter your choice and press return: "<<endl;
cin >> choice;
switch (choice){
//Add Record
case 'a':
case 'A':
record++;
cout<<"Input ID: ";
cin>>id[record];
cout<<"Input Name: ";
cin>>name[record];
cout<<"Input Price: ";
cin>>price[record];
break;
//View Record
case 'v':
case 'V':
cout<<"Enter ID you wish to view: ";
cin>>id[record];
cout<<"ID       Name        Price"<<endl;
cout<<id[record]<<"         "<<name[record]<<"      "<<price[record]<<endl;
break;
//Edit Record
case 'e':
case 'E':
cout << "Enter ID you wish to edit: ";
cin>>id[record];
cout<<"Input NEW name: ";
cin>>name[record];
cout<<"Input NEW price: ";
cin>>price[record];
break;
//Delete Record
case 'd':
case 'D':
cout << "Enter ID you wish to delete";
cin>>id[record];
id[record]=0;
name[record]=none;
price[record]=0;
break;
//View All Records
case 'l':
case 'L':
cout<<"ID       Name        Price"<<endl;
for(i=1; i<totalrecord+1; i++){
cout<<id[i]<<"      "<<name[i]<<"       "<<price[i]<<endl;
}
break;
//Exit Program if invalid input
default:
back=false;
break;
}
}
return 0;
}

好吧,一个问题是这里:

int i, j, record=0, totalrecord;
int id[record];
string name[record];
double price[record];

您正在尝试创建可变长度数组,这在C++中不受支持。不仅如此,即使支持它,您也会创建一个大小为 0 的数组,因为record = 0.

因此,对于数组的大小,需要一个不为 0 的编译时常量值。

constexpr std::size_t RECORD_SIZE = 100; // make this any other that isn't less than or equal to 0

然后,您可以像这样创建数组

int id[RECORD_SIZE];
string name[RECORD_SIZE];
double price[RECORD_SIZE];

但是,此策略的一个问题是,如果您希望记录数超过RECORD_SIZE,因为您无法调整数组的大小。因此,我建议你看看我的最后一点。

查看、编辑和删除记录时的逻辑也不正确,因为您始终访问无效索引,因为只要数组未满,record的值就会指向空槽。不仅如此,而且没有错误检查。

尽管如此,我假设您想基于索引执行这些操作。

std::size_t index = 0;
std::cin >> index;

然后,对于查看和编辑操作,您将使用该索引来操作记录。

对于删除操作,您必须将删除点右侧的记录向左移动。

但是,对于这些任务,我最终建议您使用std::vector,因为它支持您需要的所有操作,并且具有更大的动态容量。