在C++中为结构赋值

Assigning to a struct in C++

本文关键字:结构 赋值 C++      更新时间:2023-10-16

我正在尝试将新的用户输入值分配到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之间的元素。