无法让我的 getchar() 函数按我希望的方式工作,输出为 10 到 2 c++

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

我不明白为什么我的 getchar() 函数没有按我希望的方式工作。我得到的是 10 个,不是 2 个。请看一下。

主要():

#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;
}

这是我的输出:

enter a number:
220
10

最终我需要能够区分“+”“-”或字母或数字。

这可能不是最简洁的方法,但您可以一个一个地获取每个字符:

#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;
}

如果您输入例如:“250e5”,它只会得到 250 并跳过最后一个 5.

编辑: 这只是一个简单的解析器,不做任何逻辑。 如果你想制作一个计算器,我建议你看看 Stroustrup 在他的书中所做的 c++ 编程语言

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;
}