在C++中为结构赋值
Assigning to a struct in C++
我正在尝试将新的用户输入值分配到DevC++中的结构中。但是,每当它到达将用户值分配给结构的时候,程序就会崩溃,Windows就会说它停止工作。
结构如下:
struct users{
string uCode;
string lName;
string fName;
string mInit;
char type;
char gender;
} users_t[10];
这是执行任务的函数:
void createAccount(){
string newUCode;
string newLName;
string newFName;
string newMInit;
char newGender;
char newType;
system("CLS");
showBordersMain();
gotoxy(30, 6); cout << "<!-- ACCOUNT CREATION -->";
gotoxy(20, 10); cout << "USER CODE : ";
cin >> newUCode;
if (newUCode.length() > 5){
gotoxy(20, 17); cout << "USER CODE MUST BE 5 CHARACTERS IN LENGTH.n";
system("PAUSE");
createAccount();
}
for (int i = 0; i < uCount - 1; i++){
if (newUCode == users_t[i].uCode){
gotoxy(20, 17); cout << "USER CODE ALREADY EXISTS!n";
system("PAUSE");
createAccount();
}
}
gotoxy(20, 11); cout << "LAST NAME : ";
gotoxy(20, 12); cout << "FIRST NAME : ";
gotoxy(20, 13); cout << "MIDDLE INITIAL : ";
gotoxy(20, 14); cout << "GENDER [M/F] : ";
gotoxy(20, 15); cout << "ACCOUNT TYPE [A/C]: ";
gotoxy(40, 11); cin >> newLName;
gotoxy(40, 12); cin >> newFName;
gotoxy(40, 13); cin >> newMInit;
gotoxy(40, 14); cin >> newGender;
gotoxy(40, 15); cin >> newType;
//Problem starts here
users_t[uCount].uCode = newUCode;
//Program crashes before it reaches this point
users_t[uCount].lName = newLName;
users_t[uCount].fName = newFName;
users_t[uCount].mInit = newMInit;
users_t[uCount].gender = newGender;
users_t[uCount].type = newType;
gotoxy(20, 17); cout << "NEW USER ADDED!n";
system("PAUSE");
}
还有一件事,我定义了gotoxy(),如果你想知道的话,我使用的是Orwell的DevC++5.10。
我猜uCount设置为10?如果是这样的话,下面的一行很可能会导致分段故障并使您的程序崩溃
users_t[uCount].uCode = newUCode;
由于users_t是一个由10个元素组成的数组,因此您只能访问索引0和9之间的元素。
相关文章:
- 结构化绑定初始值设定项表单 { 赋值表达式 } 对于 clang 上的数组类型失败
- 如何为结构的数据元素赋值
- 复制引用结构上的赋值
- 如何为结构类型变量赋值
- 在结构的构造函数中使用类方法赋值变量
- 为可变结构赋值,该值必须易于复制
- 在 C++ 中使用 initializer_list 进行结构赋值
- C++复制可克隆层次结构中的构造函数和赋值
- C++ 带有指针、赋值和比较的结构
- Arduino结构变量似乎在没有显式重新赋值的情况下被重新赋值
- 如何使用其他函数返回的值为结构体成员赋值
- C++通用数据结构 - 数据字段赋值运算符与复制 C'Tor
- 为结构灵活数组赋值
- 在C++中添加互斥锁后结构中的赋值运算符
- 在C++中为结构赋值
- 包含字符串值的结构在使用动态内存分配创建后进行赋值时会导致分段错误
- 使用类对象为类的结构赋值
- 从C向Obj-C结构赋值
- 如何在此处为联合内部的结构赋值
- 如何为结构赋值