簡體   English   中英

為什么停止並以退出代碼11結束?

[英]Why it stops and finished with exit code 11?

我不知道為什么它會停在那里並以退出代碼11結尾。它應該一直運行到我給出命令為止。

#include <iostream>
#include <string>
#include <fstream>
using namespace std;


void record(string name, string phoneNum, int count);

// main
int main() {
    cout << " Welcome to use the Phone Contact Systerm " << endl;
    string name;
    string phoneNum;
    int count = 0;
    string signToStop;
    cout << " Please enter name and phone number " << endl;
    while ( cin >> name >> phoneNum){
        cout << " If you want to start the program, enter start "         << endl;
        cout << " If you want to quit the program, enter quit " <<     endl;
        cin >> signToStop;
        if (signToStop == "start"){
            record(name, phoneNum, count);
            cout << " Please enter name and phone number " << endl;
        }
        else if ( signToStop == "quit" ){
            break;
        }
        cout << count << endl;
        count++;


    }
}

// record all name info into Name set and record all phone numbers         into PhoneNum set
void record(string name, string phoneNum, int count){
    string Name[] = {};
    string PhoneNum[] = {};
    Name[count] = {name};
    PhoneNum[count] = {phoneNum};

    // now start to record all the info into .txt document

    ofstream phoneFile;
    phoneFile.open("contact.txt");
    phoneFile << name << "  " << phoneNum << endl;
}

結果是:

 Welcome to use the Phone Contact Systerm 

 Please enter name and phone number 

Molly 5307609829

 If you want to start the program, enter start 

 If you want to quit the program, enter quit 

start

 Please enter name and phone number 

0

Lilyi 44080809829

 If you want to start the program, enter start 

 If you want to quit the program, enter quit 

start

Process finished with exit code 11

問題是這部分在這里:

void record(string name, string phoneNum, int count){
    string Name[] = {};
    string PhoneNum[] = {};
    Name[count] = {name};
    PhoneNum[count] = {phoneNum};

    //...
}

在C ++中這很不好,因為string Name[] = {}; 而其他喜歡它的人則沒有按照您的想法去做。 他們創建一個空字符串數組。 由於可變長度數組在C ++中不是問題 ,因此會導致緩沖區溢出 ,這是未定義的行為 不好

使用std::vector代替:

void record(string name, string phoneNum){
    std::vector<std::string> Name;
    std::vector<std::string> PhoneNum;
    Name.push_back(name);
    PhoneNum.push_back(phoneNum);

    //...
}


PS您的程序中還有另一個錯誤。 也就是說,每次函數退出時, NamePhoneNum將被銷毀。 如果打算這樣做,那就很好。 如果您希望保留記錄的運行清單,那就不好了。 您可以使用靜態變量來解決此問題:

void record(string name, string phoneNum){
    static std::vector<std::string> Name;
    static std::vector<std::string> PhoneNum;
    //...
}

退出代碼11並不是C ++標准所特有的。 但是,在Linux上,該代碼通常用於表示分段錯誤。 在我的頭頂上,除了您在寫入文件后再也沒有關閉文件這一事實外,我沒有發現任何明顯的錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM