无法让我的getchar()函数工作,我想要它的工作方式,输出is10而不是2 c ++

时间:2017-09-25 05:02:22

标签: c++ getchar

我无法弄清楚为什么我的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

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

1 个答案:

答案 0 :(得分:1)

这可能不是最干净的方法,但你可以逐个获得每个字符:

#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;
}
相关问题