Problem with output(vectors)

closed account (EwCjE3v7)
Okay so when i give this program the input of "5+5", it gives me the output of 106, its supposed to be 10. Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  #include <iostream>
#include <vector>
using std::cout; using std::cin; using std::endl; // sry for this :)
using std::vector; using std::string;

int main()
{
    string input;
    vector<int> iv;
    vector<char> cv;

    cout << "Type your calculations, example \"5+5\": ";
    cin >> input;
    for (auto c : input) {
        if (isdigit(c)) {
            iv.push_back(c);
        }
        else if (ispunct(c)) {
            cv.push_back(c);
        }
    }
    if (cv[0] == '+') {
        iv[0] += iv[1];
        cout << iv[0]; // for some reason output is 106
    }
    return 0;
}
closed account (3qX21hU5)
You are storing the character representation of the numbers in the vector not the actual integer representation. The reason why is because you aren't converting them to integers before you push them into the integer vector. So what it is doing is storing the decimal value of the character (Which is this case is 53 http://www.asciitable.com/ ) in the vector instead of the actual value. This is why you are getting such a large number as a result.

To demostrate this look at this program.

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

using namespace std;

int main()
{
    char numOne = '5';
    char numTwo = '5';

    cout << numOne + numTwo;
}


To remedy this you will need to convert the character representations to integer representations before you push them into the integer vector. This is quite easy with the new C++11 helper functions for this. Or if you want to do it the old fashion way you can use std::stringstream.
Last edited on
closed account (EwCjE3v7)
Thanks you for the reply. Can you show me the c++11 way, thanks
closed account (3qX21hU5)
http://www.cplusplus.com/reference/string/stoi/
http://www.cplusplus.com/reference/string/to_string/

And their companions
closed account (EwCjE3v7)
Thanks Zereo. Great help thanks
Topic archived. No new replies allowed.