为什么循环只运行一次?

Why the loop only run one time?

本文关键字:一次 循环 运行 为什么      更新时间:2023-10-16

我试图做一个电话系统,我在main{}中使用了一个while循环。我不知道为什么它只运行一次,除非我给它停止的命令,否则它应该运行无限的时间。

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

void record(string name, int phoneNum, int count);
// main
int main() {
cout << " Welcome to use the Phone Contact Systerm " << endl;
string name;
int 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);
}
else if ( signToStop == "quit" ){
break;
}
count++;
}
}
// record all name info into Name set and record all phone numbers     into PhoneNum set
void record(string name, int phoneNum, int count){
string Name[] = {};
int 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 5307659229
Process finished with exit code 0

也许尝试 ulong int 作为电话号码,它可能太长了。另外,我可能会补充一点,我有点困惑,因为您的函数 record(( 有一个没有默认参数的第三个参数。你的问题也可能在那里。由于没有默认值,您需要在使用参数时将其放入。

正如光谱所说,电话号码并不是真正的整数,因此它不是编程(甚至数学(意义上的"数字"。

它更像是一个数字序列;也就是说,一个字符串。

当您尝试将其解释为int时,您有两个问题:

  • 您的int类型对于该值来说太小(这就是导致循环结束的原因(
  • 前导零没有意义(充其量,它用于翻转到八进制模式,这不是您想要的(。

相反,我会将其视为字符串。您仍然可以稍后对其进行验证,例如"每个字符都是数字吗?