从文件中读取 - >添加到矢量...无限循环

时间:2014-12-27 16:14:24

标签: c++ eof getline push-back

class Interacao{
  vector<string> v_line;
...
public:
  void comando_load(istringstream & iss);
};

void Interacao::comando_load(istringstream & iss){
v_line.empty();
string line;
string fname = "ini.txt";
int it = 0;

ifstream file(fname);

while (!file.eof()){
    it++;
    getline(file, line);
    cout << line << endl; //this works like it should if the line below is commented
    v_line.push_back(line); //this keeps adding line to the vector infinitely       
}
file.close();
}

我尝试做的是从文本文件中读取文件(而不是在控制台中键入它们),将它们放在字符串向量中,然后使用相同的代码读取控制台插入的命令,并进行一些修改(iss.str(line),getline(cin,line)disabled-&gt; flag),但它不会停止向向量添加行...

很抱歉非常不清楚,太困惑,无法清楚地识别/解释问题。

提前谢谢你, -ec。

编辑:&#34;完整&#34;代码

class Interacao{
    Consola c;
    vector<string> v_linha;
public:

};


void Interacao::comando_load(istringstream & iss){
    v_linha.empty();
    string linha;
    string nome_fich = "ini.txt";

    ifstream fich(nome_fich);

    while (!fich.eof()){
        getline(fich, linha);           
        v_linha.push_back(linha); //adds command from file to vector
    }
    fich.close();
}

void Interacao::Le_Comando(){

    string linha;
    Populacao* pop_jogador = nullptr;
    bool flg_pop_jgdr = 0;
    unsigned int cont = 0;

    unsigned int it = 0;
    int iComando = 0;
    int iCalls = 0;

    do{
        c.gotoxy(3, 56);  //error: this goes to a specific place on the console, it's on infinite cycle thus not allowing any action

        if (linha.length() != 0)
            c.clrcmd(linha.length());

        while (it < v_linha.size()){
            linha = v_linha[it];
            it++;
            break;
        }

        cont = v_linha.size(); //if the vector is not empty, disables cin, reads from vector instead instead cont = EOF
        if (cont == 0){
            getline(cin, linha);
        }

        if (cont > 0){ //has commands to read in vector, read 1 command, decreases cont
            cont--;
        }

        istringstream iss;
        iss.str(linha); //command

        iComando = escolheComando(iss); //converts string to int for the switch
        switch (iComando){
        case 0: //sair (exit)
            cout << "Terminou o jogo. A desligar...";
            exit(1); break;
        case 1: //load
            comando_load(iss);
            break;

        }
    } while (iComando != 0);
}

2 个答案:

答案 0 :(得分:0)

getline在最后一个输入行上失败,并在eof中设置失败位而不是fich。 结论:如果没有在循环中进行额外的测试,就不要使用while (!file.eof()){...},否则你会遇到麻烦。

答案 1 :(得分:0)

我不是一个非常聪明的人,我必须承认,发现问题,这里是:

do{
cont = v_linha.size(); //<<<<<<<< can't be inside the loop....
    if (cont == 0){
        getline(cin, linha);
    }

    if (cont > 0){ //has commands to read in vector, read 1 command, decreases cont
        cont--;  //<<<<<<<<<< ....for this to work properly...
    }
}while(...);

修正了,非常感谢你。