I have a variable (string) named eq which holds a simple equation like y=2x+5. I wanted to separate all the constants and variables. For this I declared 2 vectors:
std::vector <int> constants;
std::vector <char> variables;
I separated variables in this manner:
for(int i = 0; i < eq.size(); i++) {
if(isalpha(eq[i])) {
variables.push_back(eq[i]);
}
}
The method worked well and it separated variables like I wanted. However, when I tried the same, to separate constants, the method did not work. No matter what equation was supplied, I started getting irrelevant numbers. Equation had only 1 digit numbers like 4,3 or 5. But the vector was returning 2 digit numbers like 50, 53 or 52.
I checked the contents of the vector in this way:
for(auto j: constants) {
std::cout << j << std::endl;
}
For debugging purpose, I removed the vector.push_back
line and replaced it with std::cout << eq[i] << std::endl;
to check if the digits/numbers in the equation were being picked up. Yes the digits were being picked up, but the issue was that they weren't being inserted into the vector properly. The method worked fine for fetching variables but doesn't work for fetching constants. Where am I going wrong?
Edit: Here's the part of the code (actual code is very lengthy).
std::string eq = argv[1];
std::vector <char> variables;
std::vector <int> constants;
for(int i = 0; i < eq.size(); i++) {
if(isalpha(eq[i]) && eq[i] != 'c') {
variables.push_back(eq[i]);
}
}
for(int i = 0; i < eq.size(); i++) {
if(isdigit(eq[i])) {
constants.push_back(eq[i]);
}
}
Aucun commentaire:
Enregistrer un commentaire