2017-09-25 40 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

新的在此,謝謝你的幫助。 –