我不知道为什么它会停在那里并以退出代码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;
}
Run Code Online (Sandbox Code Playgroud)
结果是:
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
Run Code Online (Sandbox Code Playgroud)
问题是这部分在这里:
void record(string name, string phoneNum, int count){
string Name[] = {};
string PhoneNum[] = {};
Name[count] = {name};
PhoneNum[count] = {phoneNum};
//...
}
Run Code Online (Sandbox Code Playgroud)
这在C ++中是不好的,因为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);
//...
}
Run Code Online (Sandbox Code Playgroud)
PS您的程序中还有另一个错误。也就是说,Name和PhoneNum当函数每次离开都会被摧毁。如果打算这样做,那就很好。如果您希望保留记录的运行清单,那就不好了。您可以使用静态变量来解决此问题:
void record(string name, string phoneNum){
static std::vector<std::string> Name;
static std::vector<std::string> PhoneNum;
//...
}
Run Code Online (Sandbox Code Playgroud)