CRUD(添加/查看/编辑/删除/查看所有记录)
CRUD (Add/View/Edit/Delete/ViewAll Record)
我在字符串输入时遇到问题,每当我输入字符串时,程序都会停止运行,如果可能的话,请在记录上修复我的语句,因为它们似乎不能很好地工作。另外,如何删除字符串?我试图在这里用"无"代替它作为样本。提前谢谢你!
这是我的代码:
#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
,因为它支持您需要的所有操作,并且具有更大的动态容量。
相关文章:
- CRUD(添加/查看/编辑/删除/查看所有记录)
- 在二进制文件中删除记录
- 如何从 STL 列表中删除结构记录
- 删除为应该在哈希表中的记录返回 false 的函数
- 无法从我创建的 c 二进制程序中删除记录
- 从我自己的类类型的指针数组中删除记录
- STL向量和地图在删除一组记录时应该更喜欢
- 有效地删除所有重复的记录
- 基本的新建/删除操作员日志记录
- 如何在 android L 上加载 OpenCV 时删除日志记录语句
- 如何从 C 中的文件中删除记录(保存的记录是结构的)
- 从文件C++中删除记录
- 使用C++删除Internet Explorer 8历史记录、Cookie、缓存和密码
- 记录集更新和删除失败(ODBC)
- 使用数组删除记录
- 关于在c++中删除/更新txt文件中的记录
- 如何从映射中删除所有具有相同值但不同键的记录
- 在c++中删除文件中的记录
- 更新二进制文件中的学生记录,同时删除以前的数据
- 从二进制文件中删除记录