主要功能不输出文本文件行

时间:2014-09-07 23:15:53

标签: c++ console getline

以下代码应该获取一个文本文件并读取它的所有行并将它们打印到控制台上,但是虽然它正确地保存了fname,但在此之后它不会做任何事情。如果你能让我知道问题是什么,我感激不尽。

编辑:为了更准确,我最终会想要在else块中调用一些函数,但我首先要弄清楚为什么我的程序没有达到这一点。


int main()
{
    string fname = "", line, content;
    ifstream ifs; // input file stream
    string command = "";
    int k;
    cout << "---- Enter your command and the file name : ";
    while (getline(cin, line)){
        int i = 0;
        for (i = 0; i<line.length(); i++) {
            command += line[i];
            if (line[i] == ' ')
            {
                break;
            }
        }
        for (int j = i + 1; j<line.length(); j++)
        {
            fname += line[j];
        }
        cout << command;
    }

    if (command == "exit ")
    {
        exit(EXIT_SUCCESS);
    }
    // tries to open the file whose name is in string fname                 
    ifs.open(fname.c_str());

    if (ifs.fail()) {
        cerr << "ERROR: Failed to open file " << fname << endl;
        ifs.clear();
    }
    else { //do getline here to read content
        while (getline(ifs, content))
        {
            cout << "Content " << k++ << " : " << content << endl;
            //Call functions here later
        }
    }


    ifs.close(); // always remember to close it                         

    cout << "---- Enter another file and command name : ";

}

1 个答案:

答案 0 :(得分:0)

自己解决了。我太早关闭了while循环。它必须在ifs.close()之后关闭;代替。