在C ++中分配给结构体

时间:2015-03-27 14:32:24

标签: c++ struct assign

我试图将新的用户输入值分配到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。

1 个答案:

答案 0 :(得分:1)

我猜uCount设置为10?如果是这样,以下行很可能会导致分段错误并导致程序崩溃

users_t[uCount].uCode = newUCode; 

由于users_t是一个包含10个元素的数组,因此只能访问包含的索引0和9之间的元素。