为什么它停止并以退出代码 11 结束?

Why it stops and finished with exit code 11?

本文关键字:代码 结束 退出 为什么      更新时间:2023-10-16

我不知道为什么它停在那里并以退出代码 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);
//...
}

附言您的程序中还有另一个错误。也就是说,当函数每次退出时,NamePhoneNum都会被销毁。如果这是有意的,那就好了。如果您希望保留一个连续的记录列表,那就不好了。您可以使用静态变量来解决此问题:

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

退出代码 11 不是特定于C++标准的任何内容。但是,在 Linux 上,该代码通常用于表示分段错误。在我的头顶上,除了您在写入文件后从不关闭文件这一事实之外,我没有看到任何明显的错误。