0

我对 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;

}

4

2 回答 2

3

注意这里的条件:

int reply;
cin >>reply;
if (reply = 'one')
    ...

实际上是:

if (reply == 1)

放置在' '引用 single之间的文字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
}
于 2013-10-04T13:01:53.683 回答
1

你想要的是一个循环!不要相信关于 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)。

于 2013-10-04T13:02:26.413 回答