Search code examples
c++getchar

Cannot get my getchar() function to work how I want it to work, output is10 not 2 c++


I cannot figure out why my getchar() function is not working the way I want it to work. I am getting 10 not 2. Please take a look.

Main():

#include <cstdlib>
#include <iostream>
#include <fstream>

using namespace std;

int main() {
    int var, newvar;
    cout << "enter a number:" << endl;
    cin >> var;
    newvar = getchar();
    cout << newvar;

    return 0;
}

Here is my output:

enter a number:
220
10

Ultimately though I need to be able to distinguish between a '+' '-' or letter or number.


Solution

  • This is maybe not the cleanest way to do it but you can get every char one by one :

    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        int var;
        cout << "enter a number:" << endl;
        cin >> var;
        std::string str = to_string(var);
        for(int i=0; i < str.length();++i)
            cout << str.c_str()[i] << endl;
        return 0;
    }
    

    If you enter for example: "250e5" it will get only 250 and skip the last 5.

    Edit: This is just a simple parser and does not do any logic. If you want to make a calculator I would recommend you to look at what Stroustrup did in his book the c++ programming language.

    int main()
    {
        string str;
        cout << "enter a number:" << endl;
        cin >> str;
        for(int i=0; i < str.length();++i) {
            char c = str.c_str()[i];
            if(c >= '0' && c <= '9') {
                int number = c - '0';
                cout << number << endl;
            }
            else if(c == '+') {
                // do what you want with +
                cout << "got a +" << endl;
            } else if(c == '-') 
            {
                // do what you want with -
                cout << "got a -" << endl;
            }
        }
        return 0;
    }