字符串流中的字符串赋值在第一次迭代后不会改变

时间:2017-01-19 14:41:45

标签: c++ string stringstream

这真的很奇怪。如果没有ifs,则会分配字符串操作,但如果我在之间抛出ifs,则操作始终保持“暗淡”。

没有ifs的代码:

void Interaction::LoadFile(string fileName)
{
    int arg1, arg2;
    string line, action;
    vector <string> v;
    istringstream cmd;
    ifstream file;

    file.open(fileName + ".txt");
    if (file.is_open())
    {
        while (getline(file, line))
            v.push_back(line);

        file.close();

        for (int i = 0; i < v.size(); i++)
        {
            cout << i << ": " << v[i] << endl; // DEBUG PURPOSES

            cmd.str(v[i]);
            cmd >> action;

            // STRING MUST BE CLEARED??
            action.clear();
    }
    else
    {
        cout << "Can't open " << fileName << endl;
        return;
    }
}

使用ifs的代码:

void Interaction::LoadFile(string fileName)
{
    int arg1, arg2;
    string line, action;
    vector <string> v;
    istringstream cmd;
    ifstream file;

    file.open(fileName + ".txt");
    if (file.is_open())
    {
    while (getline(file, line))
        v.push_back(line);

    file.close();

    for (int i = 0; i < v.size(); i++)
    {
        cout << i << ": " << v[i] << endl;

        cmd.str(v[i]);
        cout << "CMD: " << cmd.str() << endl;
        cmd >> action;

        cout << "action: " << action << endl;

        if (getDebug())
            cout << "action : " << action << endl;

        // DIM ASSIGNMENT
        if (action == "dim")
        {
            cmd >> arg1 >> arg2;
            mapLines = arg1;
            mapColumns = arg2;
        }

        // COINS ASSIGNMENT
        if (action == "coins")
        {
            cmd >> arg1;
            coins = arg1;
        }

        // OPONENTS ASSIGNMENT
        if (action == "oponents")
        {
            cmd >> arg1;
            cout << arg1;
            numOp = arg1;
        }

        // STRING MUST BE CLEARED??
        action.clear();
    }

为什么在没有ifs的情况下动作会发生变化,但是当我添加它们时,动作总是“昏暗”?

这真的很奇怪。

提前致谢

0 个答案:

没有答案