2017-09-25 42 views
-3

我弄不明白为什么我的getchar()函数不能按我希望的方式工作。我得到10没有2.请看看。无法让我的getchar()函数工作,我希望它如何工作,输出is10不是2 C++

的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 

虽然最终我需要能够一个 '+' '来区分 - ' 或字母或数字。

+6

看起来像是捕获了'cin >> var;'留下的换行符。 – user4581301

+3

ascii代码'10'是一个换行符 – vu1p3n0x

+0

也是,如果你删除'cin >> var'你仍然不会得到'2',你会得到'50' – vu1p3n0x

回答

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”这将只得到和跳过最后的。

编辑: 这只是一个简单的解析器,并没有做任何逻辑。 如果你想制作一个计算器,我建议你看看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; 
} 
+0

谢谢你的帮助,但它不能解决我的问题。我需要能够阅读'+'或' - '或'a' - 'z'。 –

+0

@ user443355566644这并不清楚你想达到什么目的。从你的评论中,你想要逐个获取每个角色。你应该用你想要做的更多解释来重写你的问题。 – Seltymar

+0

新的在此,谢谢你的帮助。 –