返回到代码块的开头

Returning to the start of a block of code

本文关键字:开头 代码 返回      更新时间:2023-10-16

我对 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 )。