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="(减去引号)。我才刚刚开始。我试图拿出op1, op2和操作符(所有字符串)通过从文件(opString)字符逐字读取字符串(如I在for循环中所示)。while循环只是检查它是不是fstream变量的文件结束。Op1b和operb是bool值,用于确定何时"知道"第一个操作数和操作符是什么(然后确定何时可以计算出第2个操作符)。
然而,当我从字符串中提取op2时,我的op1被op2的值所取代,即使我只说op2[whatever] = opString[I],其中I远远超过op1的位置。
示例:如果从文件传入的字符串是"3+2=",op1应该得到3,oper应该得到+,op2应该得到2。然而,在循环结束时,op2总是与op1相同。因此,不是op1 = 3, oper = +, op2 = 2,而是op1 = 2, oper = +, op2 = 2。
是否有一些未记录的c++特性我错过了?我不明白为什么会发生这种情况。是因为我在循环中吗?我应该打破循环吗?然而,我看不出这有什么区别。谢谢。
下次发布完整的代码(包含所有声明)。op1
和op2
是std::string?您尝试在op1
和op2
中写入字符,但您没有分配任何空间,即您应该在循环之前使用op1.resize(SOME_SIZE)
或使用std::string::push_back
将字符附加到操作数。