我想創建一個測驗銀行遊戲....我有一個txt文件,存儲信息並將其推回到矢量,但我的主要問題是如何打印出我的get方法與這個指向矢量對象的指針? 這是我整個代碼如何打印出對象的矢量元素?
#include <iostream>
#include <string>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
using namespace std;
class question
{
private :
string ques ;
string answer;
int point ;
public :
question(string ques = "",string answer = "",int point = 0):ques(ques),answer(answer),point(point){}
virtual string getAnswer() = 0;
virtual string getQuestion() = 0;
virtual int getPoint() = 0;
};
class SAquestion : public question
{
private :
string ques ;
string answer;
int point ;
public :
SAquestion(string ques = "",string answer = "",int point = 0):ques(ques),answer(answer),point(point){}
string getAnswer() {return answer;}
string getQuestion(){return ques ;}
int getPoint() {return point ;}
};
class MCquestion : public question
{
private :
string ques ;
string answer;
int point ;
public :
MCquestion(string ques = "",string answer = "",int point = 0):ques(ques),answer(answer),point(point){}
string getAnswer() {return answer;}
string getQuestion(){return ques ;}
int getPoint() {return point ;}
};
class TFquestion : public question
{
private :
string ques ;
string answer;
int point ;
public :
TFquestion(string ques = "",string answer = "",int point = 0):ques(ques),answer(answer),point(point){}
string getAnswer() {return answer;}
string getQuestion(){return ques ;}
int getPoint() {return point ;}
};
void readDataByDelimiter(const char* filename, vector< SAquestion>*SHORTQ) {
string line;
ifstream ifs(filename);
if (ifs.is_open()) {
cout << "Reading data...\n";
int c = 0;
while (getline (ifs,line) && (*line.c_str() != '\0')) {
string delimiter = ",";
size_t pos = 0;
string* token = new string[5];
int f = -1;
while ((pos = line.find(delimiter)) != string::npos) {
token[++f] = line.substr(0, pos);
cout << " " << token[f] << " | " ;
line.erase(0, pos + delimiter.length());
}
token[++f] = line;
cout << token[f] << endl; // last item in string
c++;
// push to vector (numerical data converted to int)
SAquestion b(token[1], token[2], atoi(token[3].c_str()));
SHORTQ->push_back(b);
}
cout << c << " row(s) read." << endl << endl;
ifs.close();
}
else
cout << "Unable to open file";
}
enter code here
int main()
{
vector<SAquestion> *s = new vector<SAquestion>();
readDataByDelimiter("SHORQ.txt", s);
cout <<s[0]->getAnswer();
}
- List item
歡迎來到Stack Overflow。請花些時間閱讀[The Tour](http://stackoverflow.com/tour),並參閱[幫助中心](http://stackoverflow.com/help/asking)中的資料,瞭解您可以在這裏問。 –
解決此類問題的正確工具是您的調試器。在*堆棧溢出問題之前,您應該逐行執行您的代碼。如需更多幫助,請閱讀[如何調試小程序(由Eric Lippert撰寫)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,您應該\編輯您的問題,以包含一個[最小,完整和可驗證](http://stackoverflow.com/help/mcve)示例,該示例再現了您的問題,以及您在調試器。 –
爲什麼你動態地分配一個'vector'?您不需要,因爲C++不是Java而不是C#。通過參考您的方法。 –