-
Problem with strings
Hey guys, you were a huge help on my last problem, but here I am back again with another :\
I just need someone to help me debug my program, I've done everything I could think of to fix it, but no luck. Here's the snippet where the problem is occuring (well where the program breaks, I hope the problem isn't elsewhere)
Code:
string alg, algtemp;
j=0;
cout << endl << "Enter expression: ";
cin >> algtemp;
cout << algtemp << " =";
while (algtemp.find_first_of(')') != string::npos)
{
if (algtemp[0] != ' ' && algtemp[0] != '\t')
{
alg[j] = algtemp[0];
j++;
}
algtemp = algtemp.substr(1, string::npos);
}
pos1 = alg.find_first_of(')');
str1 = alg.substr(0, pos1);
operat = alg[pos1+1];
system("PAUSE");
alg = alg.substr(pos1+2, string::npos);
alg = algtemp;
pos2 = alg.find_first_of(')');
str2 = alg.substr(1, pos2);
The program works fine until where I have the system("PAUSE"), and then I don't get an error message or anything, the program just closes. I thought I may have been trying to access a part of the string that wasn't there, but I've tried limits that shouldn't have been close to the endpoints of the string and it still didn't work.
Oh for some backgrounds: the input I'm typing in is (2x^3)+(4x^2)
I'm trying to seperate these two polynomials into seperate polynomials in their own seperate strings, the loop there is just to make sure there's no spaces or tabs in the input.
Any help would be appreciated,
-Paul
-
1) don't use system("pause"); use std::cin.get(); and a corresponding output statement
2) substr defaults to npos as it's second argument... leave that out.
-
>> alg[j] = algtemp[0];
At that point alg has a size of zero. The operator[] is used to access existing characters in a string, so you are attempting to access memory that doesn't belong to the string. In this case you should probably get rid of j and just use += to add the algtemp[0] character to alg.