返回到代码块的开头
Returning to the start of a block of code
我对 C++ 相当陌生,但我正在制作一个简单的程序,我将如何返回代码的开头,同时仍然让它记住输入的内容。 例如,假设我按了 1 而不是输入名称,我将如何返回它询问您想要什么的主要部分。感谢您的时间,我很感激
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main(int argc, char *argv[])
{
char name[25];
char address[25];
char city[25];
char state[25];
char zip[25];
char phone[25];
int reply;
cout <<"Press 1 to enter the name"<<endl;
cout <<"Press 2 to enter the address"<<endl;
cout <<"Press 3 to enter the city"<<endl;
cout <<"Press 4 to enter the state"<<endl;
cout <<"Press 5 to enter the zip"<<endl;
cout <<"Press 6 to enter the phone"<<endl;
cin >>reply;
if (reply = 'one')
{ cout << " Enter the name" << endl;
cin >> name;
cin.ignore(80, 'n');}
else if (reply = 'two')
{cout << " Enter the address" << endl;
cin >> address;
cin.ignore(80, 'n');}
else if (reply = 'three')
{cout << " Enter the city" << endl;
cin >> city;
cin.ignore(80, 'n');}
else if (reply = 'four')
{cout << " Enter the state" << endl;
cin >> state;
cin.ignore(80, 'n');}
else if (reply = 'five')
{ cout << " Enter the zip code " << endl;
cin >> zip;
cin.ignore(80, 'n');}
else if (reply = 'six')
{ cout << " Enter the phone number " << endl;
cin >> phone;
cin.ignore(80, 'n');}
else
{cout << " done";}
system ("PAUSE");
return EXIT_SUCCESS;
}
请注意,这里的条件:
int reply;
cin >>reply;
if (reply = 'one')
...
其实是:
if (reply == 1)
放置在'
'
之间的文字是指单个char
,对于字符串,您应该使用"
"
,对于数字文字,例如int
,只需使用数字。您还应该添加一个将停止程序的选项:
cout << "Press 1 to enter the name" << endl;
cout << "Press 2 to enter the address" << endl;
...
cout << "Press 0 to stop" << endl; // <-- something like this
并用循环包装这段代码。另请注意,变量不需要在函数开头声明。
它可能看起来像这样:
// print choices (press *** to ...)
int reply;
while (cin >> reply) {
if (reply == 0)
break;
// some code...
// print choices
}
你想要的是一个循环!不要相信关于GOTO和标签的谎言!使用结构合理的代码,您始终可以避免使用这些维护噩梦。请考虑以下事项:
bool doContinue = true;
int userNumber = 0;
while( doContinue )
{
int temp = 0;
cout << "What's your next favorite number?"
cin >> temp;
userNumber += temp;
cout << "The sum of your favorite numbers is " << userNumber << endl;
cout << "Continue?" << endl;
cin >> temp;
doContinue = temp != 0;
}
这个想法是在循环之外有变量来保存循环中收集的数据。这样,您可以重复逻辑,而不必重复代码。此示例只是从用户输入中检索数字并对其进行求和,但它显示了基本循环的思想。此外,循环必须具有退出条件(在本例中为 doContinue == false
)。
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 代码在main()中运行,但在函数中出现错误
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 编译包含字符串的代码时遇到问题
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为cl.exe(Visual Studio代码)指定命令行C++版本
- 在Linux for Windows上编译C++代码时出错
- 我的字符计数代码计算错误.为什么
- 孤立代码块在结构中引发异常
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 此代码是否违反一个定义规则
- 使用代码块在链表的开头插入节点
- 为什么 C++ 中的分号在插入代码开头时不显示任何错误?
- 当我的电脑执行下面的代码时,为什么它以 5 开头
- 返回到代码块的开头
- 在链表形成中,在开头添加变量的代码是什么
- 用不同的字符串(UVa 272 - Tex 引号)替换开头和关闭 " 的代码不起作用