2013-10-04 30 views
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; 

}

+6

您可能想要了解有關循環的信息。 –

+1

=而不是==是最有名的所有時間的邏輯錯誤,首先檢查:) – iyasar

+0

我認爲在你的代碼中添加一個循環之前(這是你的問題的答案),你應該解決你已經有的問題。向錯誤代碼添加更多代碼沒有任何意義。看看LihO的回答。 – john

回答

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 
} 
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)。

+1

謝謝你們對我所有的幫助表示感謝 – user2846583

+0

有人甚至提過'goto'嗎?我看不出有什麼理由甚至把它帶到這裏... – SirGuy

+0

謝謝你們,祝你有個美好的一天,我感激不盡 – user2846583