我正在尝试制作游戏的控制台版本“我收拾行李箱......”。
基本的想法是我有一个.txt文件,里面有大约4.3k的随机名词,每行一个单词。我想读出这个文件中的单词并将它们放入vector<string>
。接下来的步骤是让另一个向量包含玩家必须记住的单词等等。
但我现在很早就开始挣扎。
几乎每次运行代码时都会发生的事情是它只是在“计算机始终启动”之后就停止了。玩得开心!打印到控制台。但是,我最后尝试了多个cout
语句,我曾经得到一些值。但他们总是不同的。例如,当打印vector.size()时,范围从0到4308(确切的行数)。在过去的30分钟里,该节目从未到过其中一个小组。
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include "player.h"
using namespace std;
int main() {
int player_score;
string player_name;
string line;
vector <string> words_list;
ifstream file;
file.open("/home/rainbowterminal/ClionProjects/PackingBags/file.txt", ios_base::in);
if(!file)
{
cerr << "Couldn't open file" << endl;
}
else
while (getline(file, line))
{
words_list.push_back(line);
}
file.close();
Player *player;
player = new Player;
cout << "Hey and welcome to 'I packed my suitcase and take with me'. You won't beat it. Promise." << endl;
cout << "To start playing just enter your name" << endl;
cin >> player_name;
player->set_name(player_name);
cout << "Okay " << player->get_name() << ", let's do this! You're a playing 'I packed my suitcase and take with me" << endl;
cout << "against the computer. Just repeat the words printed to the console" << endl;
cout << "and add an own word in the end. DO NOT seperate by commata. Letter case" << endl;
cout << "doesn't matter. Computer always starts. Have fun! " << endl;
//srand ((unsigned int) time(NULL));
//int random = (int) (rand() % words_list.size());
cout << words_list.size();
cout << words_list[100];
cout << player->get_name();
//vector<string> used_words;
//used_words.push_back(words_list[randomIndex]);
return 0;
}
正如所建议我把它分解为基本问题。这段代码会发生什么?
cout << words_list.size();
仅在50%的trys中返回向量的大小。
int main() {
string line;
vector <string> words_list;
ifstream file;
file.open("/home/rainbowterminal/ClionProjects/PackingBags/file.txt", ios_base::in);
if(!file) {
cerr << "Couldn't open file" << endl;
}
else {
while (getline(file, line)) {
words_list.push_back(line);
}
}
file.close();
cout << words_list.size();
}
如果有人能让我暗示我做错了什么,我会非常乐意自己解决这个问题。