[英]How to print ASCII value of 2 characters?
我正在尝试打印“\\ t”的ASCII值,即转义序列。 但我的程序只打印ASCII值“\\”,即ASCII值为92.有没有办法打印2个字符的ASCII值? 帮助将非常感激。我在下面包含了我的代码。
#include<stdio.h>
main()
{
char b=0;
printf("Enter any character to print it's ASCII value : ");
scanf("%c",&b);
printf("The ASCII value of '%c' is %d",b,b);
return 0;
}
捕获反斜杠的输入并将其作为单独的输入处理。 可以使用开关打印转义字符的结果。
#include <stdio.h>
int main( void) {
char b=0;
printf("Enter any character to print it's ASCII value : ");
if ( 1 == scanf(" %c",&b)) {
if ( b == '\\') {//read a backslash
if ( 1 == scanf(" %c",&b)) {
switch ( b) {
case 't' :
printf("The ASCII value of '\\t' is %d\n", '\t');
break;
case '\\' :
printf("The ASCII value of '\\' is %d\n", '\\');
break;
default :
printf ( "not handled yet\n");
}
}
}
else {
printf("The ASCII value of '%c' is %d\n",b,b);
}
}
return 0;
}
产量
输入任何字符以打印它的ASCII值:\\ t
'\\ t'的ASCII值为9
输入任何字符以打印它的ASCII值:\\\\
'\\'的ASCII值为92
要获取反斜杠的代码,必须输入两个反斜杠
此代码可能有助于您了解此处发生的情况:
#include <stdio.h>
const char* escaped(int ch) {
switch (ch) {
case '\t': return "tab";
case '\n': return "newline";
case '\r': return "carriage return";
// continue with other escaped characters
default: return "not escaped";
}
}
int main()
{
char b = 0;
printf("Enter any character to print it's ASCII value : ");
scanf("%c", &b);
printf("The ASCII value of '%c' is %d and is also known as: %s\n", b, b, escaped(b));
}
只是要非常清楚,对于标签,在键盘上只需按Tab键即可。 您不输入字符串“\\ t”。 字符串“\\ t”将被解释为2个字符:'\\'和't'。
\\ escape代码是您在C代码中编写字符串时使用的代码。 例如,如果在某些C源代码中键入字符串“尝试”,则输入字符流:尝试但是如果键入字符串:“\\ trying”,则第一个字符表示这是一个转义字符并且是一种方便的方式来表示你真的想要一个制表符后跟字符:ryin g。
使用上面的代码,如果输入“\\ t”,scanf只能从stdin获取,一次只能获得一个字符,所以它只需要第一个字符,反斜杠(转义序列的开始),然后打印出来:
Enter any character to print it's ASCII value : \t
The ASCII value of '\' is 92 and is also known as: not escaped
't'字符仍在输入流中,程序尚未处理此字符。
scanf不会将“\\ t”解释为制表符,而是将其解释为字符流\\后跟t。 那会引起你的困惑。
您将在运行此代码时遇到一些问题。 例如,您想尝试退格,即\\ b或十进制8值。 scanf可能会忽略它,并假设您正在尝试退回前一个字符。 但对于其他转义字符,如制表符和换行符,它将起作用。
#define INV (EOF -1)
int z = 0, tmp = INV;
char buff[6] = "\\0";
while (1)
{
if (tmp == INV)
z = getchar();
else
{
z = tmp;
tmp = INV;
}
if (z == EOF || tmp == EOF) break;
if (z == '\\')
{
tmp = getchar();
switch (tmp)
{
case 't':
z = '\t';
tmp = INV;
break;
case 'b':
z = '\b';
tmp = INV;
break;
case 'r':
z = '\r';
tmp = INV;
break;
case 'n':
z = '\n';
tmp = INV;
break;
// add here anothere ones
default:
break;
}
}
printf("Char \\0%03o - '%c'\t\t has the ascii code of %03d decimal 0x%02X hexadecimal\n", z, z < 32 ? ' ' : z, z, z);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.