我對C++很陌生,我試圖編寫一個系統,其中用戶正在提示選擇選項。所以當用戶選擇選項1時,它們會提示輸入7值並存儲到二維數組中。但這是存儲部件問題進入的地方,當用戶再次選擇選項1輸入7值時,數組中的值將被覆蓋。當用戶選擇選項2時,打印出的值是最新輸入值的循環。在將用戶輸入存儲到二維數組時將覆蓋值
舉例來說,輸入的第一組值爲'1,2,3,4,5,6,7',而當用戶再次選擇選項1時輸入的第二組值爲'a,b ,c,d,e,f,g',當我打印出數組時,數組只顯示g而不是7和g。
希望如果有人能就這個問題給我建議。
#include <iostream> // cin, cout
#include <fstream> // ifstream, ofstream
#include <sstream> // stringstream
#include <string>
#include <stdio.h>
#include <iomanip> // std::setw
#include <stdlib.h> /* atoi */
#include "Printer.h"
#include <termios.h> //password masking
#include <unistd.h>
using namespace std;
void displayoption(int);
void GetInput();
void DisplayInput();
void writeUserDatabase();
struct DataPile
{
// to record stock information.
string x;
string y;
string suntype;
string planet;
string moons;
string particulate;
string plasma;
};
const int MAX = 50;
Printer printer;
DataPile datapile[MAX][7];
int main()
{
system("clear");
printer.printName();
printer.printmainheader(); //display
int option =-1; //initialise int
do
{
printer.printdisplaymainmenu(); //display menu
cout<< endl<<" "<<"Enter Option :";
cin>>option;
displayoption(option);
}while(option!=5);
}
void displayoption(int option)
{
//option control functions
switch(option)
{
case 1:
GetInput();
break;
case 2:
printer.printcompute();
DisplayInput();
//addstock();
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
case 9:
break;
default:break;
}
}
void GetInput()
{
string x;
string y;
string suntype;
string planet;
string moons;
string particulate;
string plasma;
//getting input from user
cout<<"";
getline(cin, x);
cout<<"Please enter x-ordinate :";
getline(cin, x);
cout<<"Please enter y-ordinate :";
getline(cin, y);
cout<<"Please enter sun type :";
getline(cin, suntype);
cout<<"Please enter no. of earth-like planets :";
getline(cin, planet);
cout<<"Please enter no. of earth-like moons :";
getline(cin, moons);
cout<<"Please enter ave. particulate density (%-tage) :";
getline(cin, particulate);
cout<<"Please enter ave. plasma density (%-tage) :";
getline(cin, plasma);
//cout<<x<<" "<<y<<suntype<<planet<<moons<<particulate<<plasma<<endl;
//storing to array
for(int i = 1; i <=8; i++){
for (int j=1 ; j<=7 ; ++j) {
datapile[i][j].x = x;
datapile[i][j].y = y;
datapile[i][j].suntype = suntype;
datapile[i][j].moons = moons;
datapile[i][j].planet = planet;
datapile[i][j].particulate = particulate;
datapile[i][j].plasma = plasma;
}
}
cout<<" \E[1;29mRecord successfully stored. Going back to main menu\E[0m"<<endl;
printer.printName();
}
void DisplayInput()
{
string x;
string y;
string suntype;
string planet;
string moons;
string particulate;
string plasma;
for (int i=0; i<=1; i++)
{
for(int j=0; j<=6; j++)
{
cout << datapile[i][j].plasma<<endl;
}
}
}
使用調試器逐行執行代碼,在這方面做得比在SO上做得更好。 – 2015-04-03 10:00:29
TL; DR!請嘗試將代碼縮小到導致問題的部分。最好的是創建一個[最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)並向我們展示。 – 2015-04-03 10:03:55