为什么它停止并以退出代码 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);
//...
}
附言您的程序中还有另一个错误。也就是说,当函数每次退出时,Name
和PhoneNum
都会被销毁。如果这是有意的,那就好了。如果您希望保留一个连续的记录列表,那就不好了。您可以使用静态变量来解决此问题:
void record(string name, string phoneNum){
static std::vector<std::string> Name;
static std::vector<std::string> PhoneNum;
//...
}
退出代码 11 不是特定于C++标准的任何内容。但是,在 Linux 上,该代码通常用于表示分段错误。在我的头顶上,除了您在写入文件后从不关闭文件这一事实之外,我没有看到任何明显的错误。
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 为什么在这个代码结束循环中没有得到结束
- 程序显示以退出代码 0; 结束
- 为什么这个 while 循环在下面的代码中没有结束?
- 为什么它停止并以退出代码 11 结束?
- 程序过早结束,可能已经崩溃了.退出代码0xc0000005
- C 功能:读取直到文件结束 - 查找代码中的错误
- 如何直接从构造函数结束C 代码
- 如何停止任务运行终端在程序以视觉工作室代码结束后自动退出
- 堆叠C++代码工作正常,但在运行代码结束时"glibc detected"
- 结束进程错误代码 -1,如果访问结构的字符串字段
- 如何删除此代码输出的结束空格
- 在批处理文件上进行C++fstream写入,然后结束,没有剩余的代码行
- 代码在嵌套开关中选择的每个情况和错误C4244在c++中从double转换为float后停止/结束
- c++代码工作正常,但进程以termination结束,而不是返回0
- C代码在GOP(Group of Pictures)结束处剪切mpeg2视频
- 在这段代码中,我有一个警告:控制达到非void函数的结束[- return-type].我怎样才能解决这个问题
- 代码无法打印出整个字符串并突然结束
- 在<int>代码块结束之前释放分配给 std::vector 的内存的正确方法
- 如何结束C++代码