gpt4 book ai didi

c++ - 返回到代码块的开头

转载 作者:行者123 更新时间:2023-11-27 23:12:31 27 4
gpt4 key购买 nike

我是 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
}

关于c++ - 返回到代码块的开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19181755/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com