简体   繁体   English

将整数转换为C中的字符(根据ASCII表)

[英]converting integers to chars in C(according to ASCII table)

been searching everywhere, but couldn't the correct answer. 一直在寻找,但无法正确答案。

the problem is pretty simple: 问题很简单:

i have to convert ASCII integer values into char's. 我必须将ASCII整数值转换为char。 for example, according to ASCII table, 108 stands for 'h' char. 例如,根据ASCII表,108代表'h'char。 But when i try to convert it like this: 但当我尝试将其转换为这样:

int i = 108
char x = i

and when I printf it, it shows me 's', no matter what number i type in(94,111...). 当我打印它时,它显示我的',无论我输入什么号码(94,111 ...)。

i tried this as well: 我试过这个:

int i = 108;
char x = i + '0'

but i get the same problem! 但我得到同样的问题! by the way, i have no problem in converting chars into integers, so i don't get where's the problem :/ thanks in advance 顺便说一句,我把字符转换成整数没有问题,所以我不知道问题出在哪里:/提前谢谢

That is how you do it. 你就是这样做的。 You probably want it unsigned, though. 但是你可能希望它没有签名。

Maybe your printf is wrong? 也许你的printf错了?

The following is an example of it working: 以下是它工作的一个例子:

// Print a to z.
int i;
for (i = 97; i <= 122; i++) {
    unsigned char x = i;
    printf("%c", x);
}

This prints abcdefghijklmnopqrstuvwxyz as expected. 按预期打印abcdefghijklmnopqrstuvwxyz (See it at ideone ) (在ideone上看到它)

Note, you could just as well printf("%c", i); 注意,你也可以printf("%c", i); directly; 直; char is simply a smaller integer type. char只是一个较小的整数类型。

If you're trying to do printf("%s", x); 如果你想做printf("%s", x); , note that this is not correct. ,请注意这是不正确的。 %s means print as string, however a character is not a string. %s表示打印为字符串,但字符不是字符串。

If you do this, it'll treat the value of x as a memory address and start reading a string from there until it hits a \\0 . 如果你这样做,它会将x的值视为内存地址,并从那里开始读取一个字符串,直到它达到\\0 If this merely resulted in printing s , you're lucky. 如果这仅仅是导致印刷s ,你是幸运的。 You're more likely to end up getting a segmentation fault doing this, as you'll end up accessing some memory that is most likely not yours. 你更有可能最终得到一个分段错误,因为你最终会访问一些很可能不是你的内存。 (And almost surely not what you want.) (而且几乎肯定不是你想要的。)

Sounds to me like your printf statement is incorrect. 听起来像你的printf语句不正确。

Doing printf("%c", c) where c has the value 108 will print the letter l ... If you look at http://www.asciitable.com/ you'll see that 108 is not h ;) 执行printf("%c", c) ,其中c的值为108将打印字母l ...如果你看http://www.asciitable.com/你会看到108不是h ;)

I'm guessing your printf statement looks like this: 我猜你的printf语句看起来像这样:

printf("s", x);

..when in fact you probably meant: ..实际上你可能意味着:

printf("%s", x);

...which is still wrong; ......这仍然是错的; this is expecting a string of characters eg: 这是期待一串字符,例如:

char* x = "Testing";
printf("%s", x);

What you really want is this: 你真正想要的是这个:

int i = 108;
char x = i + '0';
printf("%c", x);

...which on my system outputs £ ...在我的系统上输出£

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM