2013-04-17 42 views
0

我正在編寫一個程序,它將請求用戶輸入INT,並將其存儲在[10]的數組中。我希望能夠讓用戶選擇DISPLAY選項並查看數組中的所有數據。我只是想不通,這裏是我到目前爲止有:關於將輸入存儲到字符串中,並使用cout來顯示它

case 2 : { 
       int SamtW; 
       cout << " Please enter how much you would like to withdraw "<< endl; 
       cin >> SamtW; 
       sa.doWithdraw(SamtW); 
       break; 
      } 

這裏是正在調用的函數上面:

int saving:: doWithdraw(int amount) 
{ 
    for (int i = 0; i < 10; i++) 
{ 
    last10withdraws[amount]; 
    } 
    if (amount > 1) 
    { 
    setBalanceW(amount); 
    } 
    else { 
     cout << " ERROR. Number must be greater then zero. " << endl; 
    } 
    return 0; 
} 

我相信這將會把用戶輸入到字符串last10withdraws。然後我希望用戶能夠調用此函數:

string saving::display() 
{ 
    last10withdraws[10]; 
    return 0; 
} 

並且這將有望顯示數組的內容。關於我做錯什麼的想法?

+0

什麼的在'doWithdraw'循環的目的是什麼?它現在沒有意義。 – stardust

+0

我希望它把int amount的參數放入數組last10withdraws中。 – Dolbyover

+0

這並非如此,但可以等待。 **你想放哪?在整個陣列?我的意思是陣列中的所有10個位置?** – stardust

回答

1
last10withdraws[10]; 

這什麼都不做。這需要數組的第11個元素的值(不存在),然後將其丟棄。

同樣這樣的:

last10withdraws[amount]; 

last10withdraws一個元素的值並拋出它扔掉。它不會爲其分配任何價值或將其存儲在任何地方。

我想你想:

int saving:: doWithdraw(int amount) 
{ 
    if (amount > 0) 
    { 
     for (int i = 9; i != 0; i--) 
     { // move the 9 elements we're keeping up one 
      last10withdraws[i] = last10withdraws[i-1]; 
     } 
     last10withdraws[0] = amount; // add the latest 
     setBalanceW(amount); // process the withdraw 
    } 
    else 
    { 
     cout << " ERROR. Number must be greater then zero. " << endl; 
    } 
    return 0; 
} 
0

OK從您的評論:

首先,你需要在你的saving稱爲像nr_of_withdraws一個額外的變量。它將跟蹤已經制造了多少withdraws。在課程結束時它應該被分配到零。

然後每次插入到last10withdraws時,您都會增加nr_of_withdraws。如果nr_of_withdraws大於9,那麼你的數組已滿,你需要做些什麼。所以......


// Constructor. 
saving::saving { 
    nr_of_withdraws = 0; 
} 

// doWithdraw 
int saving:: doWithdraw(int amount) 
{ 
    // See if you have space 
    if(nr_of_withdraws > 9) 
     cout << "last10withdraws are done. Slow down." 
     return 0; 
    } 
    // These lines. oh thy are needed. 
    last10withdraws[nr_of_withdraws] = amount; 
    nr_of_withdraws++; 

    if (amount > 1) 
    { 
     setBalanceW(amount); 
    } 
    else { 
     cout << " ERROR. Number must be greater then zero. " << endl; 
    } 
    return 0; 
} 
+0

好的我繼續把它放在我的代碼中,但我仍然在調用顯示函數時遇到問題。我將如何能夠調用它並讓它顯示數組中的所有數據? – Dolbyover

相關問題