所以我试图从文本文件中读取值用逗号分隔,然后我想将它存储到一个向量中。我是c +的新手,我很难习惯它。到目前为止,我所做的是读取文件,存储在std::vector<string>
然后将数据拆分为该矢量,其中用逗号分隔,然后我尝试循环并使用字符串值创建Room
个对象位置。我不知道我做错了什么,但每当我尝试打印什么都没有出现在cmd线上。我不知道我做错了什么。有另一种方式吗?为什么不在命令中打印。这是我到目前为止所做的:
vector<string> split_at_commas(const string& row)
{
vector<string> res;
istringstream buf(row);
string s;
while (getline(buf, s, ','))
res.push_back(s);
return res;
}
static void loadRooms() {
ifstream input("room.txt"); //Go find the file
if (input.is_open()) {
while (!input.eof()) {
string fileData;
string myData;
getline(input, fileData); //read fileData
myData = fileData; //now fileData is myData
datas = split_at_commas(myData);
//string iddata = dataFromFile[0]
//string name = dataFromFile[1];
//string description = dataFromFile[2];
//int id = std::stoi(iddata);
//for each (string var in datas)
//{
// cout << var << endl; //print it out
//}
//cout << datas << endl; //print it out
}
}
}
static void createRooms() {
for (size_t i = 0; i < datas.size(); i++) {
Room r;
r.setRoomId(stoi(datas[0]));
r.setRoomName(datas[1]);
r.setRoomDescription(datas[2]);
room.push_back(r);
}
}
int main() { //Application Interaction
loadRooms();
createRooms();
/* giving users options and based on the enetered input an action is executed
I decided to use numbers for users options intead
*/
cout << "Chose what to do Next(Enter Number) \n";
cout << "1. Explore your current room (Enter 1) \n";
cout << "2. Process to North (Enter 2) \n";
system("PAUSE");
}
输入文件的工作示例:
1,Generator Room, This is the starting line. welcome to ZombieScare where it gets real. Your at the starting line
and you've only got one option which is to turn proceed to the north of here.But dont forget to explore this room.
2, Activate power, You are in a room north of the room you started from and your presented with 2 electrical doors.
You need to turn on the power in this room... Lucky for you your next to the power generator. ACTIVATE THE POWER GENERATOR!
3, Robotic Arival, you sucessfully activated power and chose to proceed to the eastern room.. SUPRISE The Amoured Robot Zombie Spawned!!
What to do?
setRoom
setName
void Room::setRoomId(int id)
{
roomId = id;
}
void Room::setRoomName(string rmName)
{
roomName = rmName;
}
void Room::setRoomDescription(string rmDesc)
{
roomDescription = rmDesc;
}
请任何帮助都会很棒。我不知道这有什么不对。谢谢
答案 0 :(得分:1)
在每次迭代中,您都会覆盖datas
。这意味着,在createRooms
,仅从最后一个拆分值创建的房间。
您可能在文件的最后一个字符串处有新行。在最后一次迭代中,myData
变为空字符串,并且您获得了空datas
向量。最后没有任何内容打印到控制台。
在datas
的循环内访问createRooms
值是可疑的:
r.setRoomId(stoi(datas[0]));
r.setRoomName(datas[1]);
r.setRoomDescription(datas[2]);
为什么要按i
进行迭代并按0,1,2进行访问?看起来您希望vector<vector<string>>
保留每个拆分结果。
顺便说一句,条件:
while (!input.eof())
是bad approach来完成文件读取。