I don't know why it stops there and finished with exit code 11. It suppose to run until I give the command.
#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;
}
Result is:
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
Exit code 11 is not anything specific to the C++ standard. However, on Linux that code is generally used to represent a segmentation fault. Off the top of my head, I don't see anything glaringly wrong other than the fact that you never close the file after you write to it.
The problem is this part right here:
That's bad in C++ because
string Name[] = {};
and others like it don't do what you think they do. They create an empty array of strings. Since variable length arrays are not a thing in C++, this creates a buffer overflow, which is undefined behavior. That's bad.Use a
std::vector
instead:P.S. There is another bug in your program. That is,
Name
andPhoneNum
will get destroyed when the function exits each time. If that is intended, then fine. If you wish to keep a running list of records, that is bad. You can use a static variable to fix this: