2017-04-25 59 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”。 –