I've been working on a parser for a while and i seem to be having an error with a certain bit of code "find first not of". The main issue i'm having is that whenever I enter a number bigger than 99 the program only reads the first two numbers.
string.legnth; //assume it is 5+500
string token_1; //declaration of token 1 & 2
string token_2;
size_t pos_1 = 0; //pos_1 necessary to save point on a string
int addition = 0;
double answer = 0;
for (int i = 0; i < input.length(); ++i)
{
if(isdigit(input[i]) && answer == 0)
{
pos_1 = input.find_first_not_of("1234567890");
token_1 = input.substr(0, pos_1+1);
cout << "token_1=" << token_1 << endl;
answer = stoi(token_1);
token_1 = "";
}
elseif (isdigit(input[i]) && answer != 0)
{
continue;
}
elseif (input[i] == '+')
{
input[i] = 'A';
pos_1 = input.find_first_not_of("1234567890");
token_2 = input.substr(i+1, pos_1+1);
cout << "token_2=" << token_2 << endl;
answer += stoi(token_2);
What's weird is that when I enter 500+5 it will work for the first number but not for the second number/token. Does anyone have any ideas? Also if you have any questions please ask.
IMPORTANT!!: you don't have to look at the entire code but here it is if you're truly interested.
Also be careful with the string.find functions. These functions return a value between zero and std::string::npos with zero being the first character of the string and std::string::npos is std::numeric_limits<std::string::size_type>::max(), the value that represents the largest possible std::string.length(). This usually indicates that the find() was unsuccessful.
So in the following snippet if the first character is not a digit pos_1 will equal zero.
If however there are only digits in the string pos_1 will be equal to std::string::npos and in this case trying to add one to this value will also yield a value of zero.
I'm sorry I'm not great with programming terminology. I entered 5+500 for the input. I found that I can get the first token just fine, but the real issue is the second token.
i did find a solution for the problem although I'm not so sure how it works, but here it is
I added the length of the string to pos_1, but shouldn't that = the current position of pos_1 + the entire length of the string? I've also added values like 1000 and have seen similar results.
Update: even if i add pos_1 - input.length() it still works. Heck I'm sure i could put pos_1 - unicorn and it would still work...Am I drunk
what's a string stream? Also for this parser I want it to be able to read everything the user enters not just 2 values. It does seem like a good basic code though I could probably use it for a function. thanks