为什么循环只运行一次?
Why the loop only run one time?
我试图做一个电话系统,我在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
类型对于该值来说太小(这就是导致循环结束的原因( - 前导零没有意义(充其量,它用于翻转到八进制模式,这不是您想要的(。
相反,我会将其视为字符串。您仍然可以稍后对其进行验证,例如"每个字符都是数字吗?
相关文章:
- 循环中的条件:为什么每次都调用strlen(),而vector.size()只调用一次
- (C++)虽然循环一次不起作用,但我引入了多个变量
- 花括号使循环运行一次?
- 从子菜单返回后,正确的输入至少进入验证循环一次
- foor 循环的最后一次迭代中的指针更改
- 有没有办法在循环中的条件至少满足一次时运行语句?
- 循环中本地对象的析构函数是否保证在下一次迭代之前被调用?
- For循环在cpp中仅执行一次
- 如何强制循环执行另一次迭代到零并关闭循环
- (C++)for循环中的空初始语句是否保存所有编译器中变量的上一次初始化
- 为什么在C/C++中的while循环中只发生一次取消引用
- 如何防止我的循环额外运行一次?
- Atmel Studio 7:ASF 库提供的 USART 中断处理程序仅在 main() 中遇到无限循环时工作一次?
- 如何在主游戏循环中使用 sfml 只播放一次声音
- 当我输入一个字母时,cin 输入(输入是一个 int),而不是打印错误一次,它打印正确一次,然后在循环的其余部分打印 i
- C++,查找最低值,函数错误:循环最多运行一次(循环增量从未执行)
- boost::multi_index_container:从任意索引中取equal_range,只实现一次循环
- 使用sleep_for每毫秒运行一次循环
- 循环将最多运行一次(循环增量永远不会执行)
- 为什么函数立即完成一次循环,然后再次运行