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)

の間に配置されたリテラル' 'は、単一の参照を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 と LABEL に関する嘘を信じないでください。適切に構造化されたコードを使用すると、これらのメンテナンスの悪夢を常に避けることができます。次の点を考慮してください。

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 に答える