如何将char值转换为int?

时间:2015-02-28 09:25:59

标签: c++ char integer int

最后我想用char乘以int,这是不可能的。如何得到像整数的x值?

{
char a[50];
int y;
    printf("Vyvedete imeto si i razberete koe e shtastlivoto vi chislo\n");
    cin >> a;
int x = printf(a) * 5;
    printf(" Your lucky number is %d\n", x);
    printf("But wait! There is more!\n Type another number!\n");
    cin >> y;
    printf(y*x);
return 0;

}

3 个答案:

答案 0 :(得分:2)

你试过这个:?

#include<stdio.h>
int main(void)
{
    char c='d';
    printf("the character before multiplication is %c and ascii representation is %d",c,c);
    int x=c*5;
    printf("the character after multiplication is %c and ascii representation is %d",x,x);
}

答案 1 :(得分:0)

  

如何在C中将char值转换为int?

char 整数。

#include <stdio.h>

...

char c = 'A';
printf("%d\n", c);

int i = c;
printf("%d\n", i);

i = 'B';
printf("%d\n", i);

c = i; /* For this you might get warned about loosing 
          significant digits during conversion as 
          char is 8 bit wide and int is wider. */
printf("%d\n", c);

打印

65
65
66
66

答案 2 :(得分:0)

将您的代码更改为:

char a[50]=""; //initialize a
printf("Vyvedete imeto si i razberete koe e shtastlivoto vi chislo\n");
cin >> a; //better to use fgets/scanf
int x = strlen(a) * 5; //use strlen from string.h to get the length of a
printf(" Your lucky number is %d\n", x);

请注意,将C样式代码与C ++混合是一种不好的做法。使用coutcinprintfscanf。另请注意,如果要使用string.h函数,则需要包含cstdlibstrlen for C ++)。如果您使用的是C ++,则建议使用string数据类型。