无法使我的getChar()函数能够工作,我希望它能正常工作,输出IS10而不是2 C

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

本文关键字:工作 IS10 输出 常工作 函数 我的 我希望 getChar      更新时间:2023-10-16

我无法弄清楚为什么我的getchar()函数无法按照我希望其工作方式工作。我要获得10个而不是2。请看看

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

这是我的输出:

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