回到一段代码的开头

时间:2013-10-04 12:56:27

标签: c++ loops input io

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

}

2 个答案:

答案 0 :(得分:3)

请注意这里的条件:

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

实际上意味着:

if (reply == 1)

' '之间的文字引用单个char,您应该使用" "的字符串和{{1}等数字文字只需使用数字。您还应该添加一个停止程序的选项:

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

答案 1 :(得分: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)。