0

I am trying to make a more advanced calculator where you enter a piece of algebra. I have this problem, the string that contains what you inputted doesn't test positive for '+' even when it does.

This is the code that tests the string

for(int i = 0; i < line.length(); i++)
{
    if(pos == 0 && line[i] >= '0' && line[i] <= '9' || line[i] == '.')
    {           
        p1[p1p] = line[i]; // setting the number to the current character
        p1p++; // position of the first number  
    }
    if(line[i] == '+')
    {
    pos++; 
    operation = 1;
    cout << "add" << endl;
    }
}

It will never out put + unless there is no space between the last character of the number and the + symbol

e.g. '100+10' would test positive for '+' but '100 + 10' wouldn't.

Thanks -Hugh

4

2 回答 2

1

If my guess is correct you input the data with std::cin. which is why it does not read characters after the first white space.

use getline() function instead.

于 2013-02-13T03:29:43.997 回答
0

You could use the operator>> which naturally reads (optionally) space separated values.

int val;
while(std::cin >> val)
{
    // We have a value (an integer)

    char c;
    if (std::cin >> c)
    {
        // we have read the next non space character
        switch(c)
        {
            case '+': std::cout << "Adding: " << val << "\n";break;
        }
    }
}
于 2013-02-13T05:24:00.730 回答