简体   繁体   English

C-扫描字符并显示ASCII码

[英]C - Scan chars and show ASCII code

This is a super basic question... I am relearning C (haven't used it for more than 5 years). 这是一个超级基本的问题……我在学习C(已经使用了5年以上)。 I can't get this code to work. 我无法使此代码正常工作。 I am trying to scan a user input (ascii character) as an integer, and show the ascii code for the entered character. 我试图将用户输入(ASCII字符)扫描为整数,并显示输入字符的ASCII代码。

#include <stdio.h>
int main(int argc, char *argv[]) {

  int character;

  printf("Welcome to ASCII:\n");

  do {
    scanf("%d",&character);

    printf("ascii: %d\n",character);
  } while(character != 999);

  printf("Done.\n");

  return 0;
}

It just shows 0 for every input... 每个输入只显示0 ...

" I am trying to scan a user input (ascii character) as an integer, and show the ascii code for the entered character" “我正在尝试将用户输入(ASCII字符)扫描为整数,并显示输入字符的ASCII代码”

What you should do is exact opposite. 您应该做的恰恰相反。 You should read a character and display it as an integer, ie: 您应该阅读一个字符并将其显示为整数,即:

char c;
scanf("%c", &c);    // <-- read character
printf("%d", c);    // <-- display its integral value

input: a , output: 97 输入: a ,输出: 97


Also note that while(character != 999) isn't very lucky choice for a terminating condition of your loop. 还要注意,对于循环的终止条件, while(character != 999)不是很幸运的选择。 Checking the return value of scanf to determine whether the reading of character was successful might be more reasonable here: 在这里检查scanf的返回值以确定字符读取是否成功可能更合理:

while (scanf("%c", &character)) {
    printf("ascii: %d\n", character);
}

try this: 尝试这个:

    #include <stdio.h>
int main(int argc, char *argv[]) {

  char character;

  printf("Welcome to ASCII:\n");

  do {
    scanf("%c",&character);
    getchar(); // to get rid of enter after input

    printf("ascii: %d\n",character);
  } while(character != 999);

  printf("Done.\n");

  return 0;
}

output: 输出:

d
ascii: 100
s
ascii: 115

You are trying to read an integer(scanf("%d", &...)) and it's normal this operation to fail and the value to be 0 - a default value for int variable. 您正在尝试读取一个整数(scanf(“%d”,&...)),此操作通常会失败,并且该值将为0-int变量的默认值,这很正常。 Change the "%d" to "%c" and it should work. 将“%d”更改为“%c”,它应该可以工作。

change to : 改成 :

printf("ascii: %c\n",character);

However , What your condition speciftied 999 ? 但是,您发现999的情况如何?

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

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