2017-04-25 49 views
1

例如:給char類型賦一個數字做算術運算?

char X = 3; 
char Y = 6; 
char Z = 9; 
int scoreAll, score1, score2, score3; 

cin >> score1 >> score2 >> score3; // user should enter X >> Y >> Z 

scoreAll = score1 + score2 + score3; 

cout << scoreAll // output should be 18 

是有C++中的方式來分配INT號碼到類型,然後使用另一個變量在其上執行算術運算?

基本上我想要鍵入一個字符X和和使編譯器動作等我輸入3.


附加說明: 用戶輸入多個字符,「XYXXZ」,例如,每個字符有它自己的值,編譯器現在應該添加這些字符的值並將結果作爲整數輸出(「XYXXZ」的結果應該是= 24)。

+1

可以使用switch.int GETVAL(炭X) { \t開關(X) \t { \t \t情況下 'X': \t \t \t返回3; \t \t'Y': \t \t \t return 6; \t \t case'z': \t \t \t return 9; \t} \t返回-1; //無效的輸入 } – user1438832

+3

有沒有辦法讓用戶輸入一個字符或字符串,並用它來引用變量的名稱,如果這是你的意思。你需要自己做。源代碼中的名稱和程序中的值是獨立的Universe。 – molbdnilo

+2

你的問題和泥一樣清晰。嘗試提供一些你的意思的概念性例子。 – Peter

回答

2

您可以使用std::map到你的角色/變量名映射到值。用戶可以插入則字符X,Y和Z:

std::map<char,int> values; 
value['X'] = 3; 
value['Y'] = 6; 
value['Z'] = 9; 
char score1, score2, score3; 

//Here it would be advisable to check cin status/success 
cin >> score1 >> score2 >> score3; 

cout << value[score1] + value[score2] + value[score3] << std::endl; 

的一些想法checking cin status

+0

是的,這將工作。不要忘記檢查'cin'的狀態/成功。 –

+0

@BoundaryImposition謝謝!我想知道downvote! – Antonio

+0

@Antonio不用擔心downvotes,因爲你做到了,非常感謝:) – BeyondNero

-3

嘗試:

int main() 
{ 

    char X = 3; 
    char Y = 6; 
    char Z = 9; 

    int scoreAll; 
    cin >> X >> Y >> Z; 
    scoreAll = X + Y + Z; 
    cout << scoreAll; 
    return 0; 
} 

另一種方式:

int main() 
{ 
    char X; 
    cin >> X; 
    printf("%d",X - 85); 
    return 0; 
} 
-1

既然你想要的是從用戶輸入的AA數值轉換,但被解讀爲char型,最簡單的方法是將其轉換爲int。

int main() 
{ 
    char x, y, z; 
    std::cin >> x >> y >> z; 
    int result = atoi(x) + atoi(y) + atoi(z); 
} 

的atoi將數字字母轉換爲數字,甚至吼聲,他們看起來是一樣的,「1」是不是1

+0

這不是他們想要的(儘管這個問題很不明顯)。他們需要用戶驅動的「變量變量」。 –

0

這是一個可怕的方式做到這一點

老實說你所有使用您的解決方案後,應使用類似於C++的地圖容器

#include <map> 
#include <stdio.h> 
#include <iostream> 
#include <string> 

int main() 
{ 
    std::map<std::string, int> map; 
    map["X"] = 3; 
    map["Y"] = 6; 
    map["Z"] = 9; 

    std::string res = ""; 
    std::cin >> res; 

    for (std::map<std::string, int>::iterator it = map.begin(); it != map.end(); ++it) 
    { 
    if (it->first == res) 
    std::cout << it->second << std::endl; 
    } 
} 

(但你應該使用另外一個),你可以這樣做

#include <string> 
#include <iostream> 
#include <stdio.h> 

#define PRINTER(name) printer(#name, (name)) 

std::string printer(char *name, int value) { 
    std::string res (name); 
    return res; 
} 

int main() 
{ 
    char X = 3; 
    char Y = 6; 
    char Z = 9; 

    std::string res = ""; 
    std::cin >> res; 

    if (res == PRINTER(X)) 
    std::cout << (int)X << std::endl; 
} 
+0

在最近的C++中不起作用;使用'const char * name' –

+0

它的工作原理+ C++標準建議使用std :: string – RomMer

+0

不,它不起作用。在C++ 98和C++ 03中,字符串文字到'char *'的轉換已棄用;從C++ 11開始,它就是_illegal_。此外,在你聲稱的情況下,C++標準確實_not_「建議使用std :: string」。 –