C ++一次为两个字符串赋值

时间:2011-04-10 04:31:41

标签: c++ string variable-assignment

    unsigned short n = 0;
    while (!in.eof())
    {
        in >> opString;     //Read in string from file
        //Read the string from file character by character
        for (int i = 0; i < opString.size(); i++)
        {
            if (!op1b)  //If we do not yet know our first operand (op1b = false, b stands for bool, clever naming eh?)
            {       //Check if our next item is an operator. If it is...
                if (!(opString[i] == '+' || opString[i] == '-' || opString[i] == '*' || opString[i] == '/' || opString[i] == '$'))
                    op1[i] = opString[i];
                else        //We finally know it since when we hit an symbol, our first number is known; do not repeat this if block
                    op1b = true;                
                n++;
            }

            if (op1b && !operb)     //If we know our first operand but not our operator...
            {
                oper = opString[i];     //Find out what our operator is.  Now we know it (operb = true)
                operb = true;
                i++;                //We increment i because if we did not we'd double dip on the if statement below and wind up
            }                           // with an operator tacked onto the beginning of the second operand

            if (op1b && operb)      //If we know our first operand and the operation, let's find operand #2
            {
                if (opString[i] == '=')
                    break;
                else
                {
                    op2[i-n] = opString[i];
                    j++;
                }
            }
        }
        cout << "Op 1: " << op1.c_str() << endl << "Oper: " << oper.c_str() << endl << "Op 2: " << op2.c_str() << endl;
    }
    return 0;
}

我所拥有的是一个程序的开头,该程序旨在从文本文件中读取字符串以将十六进制操作数添加到一起。字符串的形式为“op1OperatorOp2 =”(减去引号)。我刚开始。我试图通过逐字符读取文件中的字符串(opString)来取出op1,op2和操作符(所有字符串)(如for循环中的i所示)。 while循环只是检查它不是fstream变量的文件结尾。 op1b和operb是bool值,有助于确定我们何时'知道'我们的第一个操作数和操作符是什么(然后我们何时可以计算出操作符号2)。

然而,当我从字符串中提取op2时,我的op1被替换为op2的值,即使我只说op2 [whatever] = opString [i],其中我很久以前就是op1。

示例:如果从文件进入的字符串是“3 + 2 =”,则op1应为3,oper应为+,op2应为2.但是,op2总是与op1相同循环结束。因此,代替op1 = 3,oper = +,op2 = 2,我最终得到op1 = 2,oper = +,op2 = 2.

我缺少一些未记录的C ++功能吗?我无法弄清楚为什么会这样。是因为我在循环中吗?我应该打破我的循环吗?但是,我不明白为什么那应该有所作为。感谢。

1 个答案:

答案 0 :(得分:1)

下次发布完整代码(全部解除)。 op1op2是std :: string吗?您尝试在op1op2中写字符但是您没有分配任何空格,即您应该在循环之前op1.resize(SOME_SIZE)或使用std::string::push_back将字符附加到操作数。