Reputation: 2361
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;
}
What I have here is (the beginning of) a program that is meant to read in strings from a text file to add hexadecimal operands together. The strings have the form of "op1OperatorOp2=" (minus the quotation marks). I am just starting. I am trying to take out op1, op2, and the operator (all strings) out of that by reading the string from the file (opString) character by character (as indicated by i in the for loop). The while loop just checks that it's not end of file for the fstream variable. op1b and operb are bool values that help determine when we 'know' what our first operand and operator are (and then when we can figure out operator number 2).
However, when I extract op2 from the string, my op1 gets replaced with the value of op2, even when I only say op2[whatever] = opString[i] where i is long past where op1 would even be.
Example: if the string coming in from the file is "3+2=", op1 should get 3, oper should get +, and op2 should get 2. However, op2 always ends up being the same as op1 at the end of the loop. Thus, instead of op1 = 3, oper = +, op2 = 2, I end up with op1 = 2, oper = +, op2 = 2.
Is there some undocumented C++ feature I am missing? I cannot figure out why this occurs. Is it because I am in a loop? Should I break up my loop? I do not see why that should make a difference, however. Thanks.
Upvotes: 0
Views: 265
Reputation: 1389
Next time post complete code (with all declration). op1
and op2
are std::string? You try to write characters in op1
and op2
but you haven't allocated any space, i.e. you should either op1.resize(SOME_SIZE)
before the loop or use std::string::push_back
to append chars to the operands.
Upvotes: 1