简体   繁体   English

读取几个ASCII字符并获取值

[英]Read several ASCII characters and get the value

Can someone explain or correct me on the code i have? 有人可以解释或纠正我的代码吗? I'm trying to input several characters and get the ascii value 我正在尝试输入几个字符并获得ascii值

ex: input: ab; 例如:输入:ab; output:9798 输出:9798

This is my code but there's a 10 at the end of it 这是我的代码,但最后有一个10

#include <stdio.h>

int main() { 
    char c;
    printf("Enter any character\n");

    for (c=0; c<=122; c++)
    {
        scanf("%c", &c);
        printf("%d",c);
    }
    return 0;
}

If you look at ASCII table , a decimal value of 10 is a newline character. 如果查看ASCII表 ,则十进制值为10是换行符。 In other words, you process \\n character as part of the input. 换句话说,您将\\n字符作为输入的一部分处理。 This can happen when user copy-pastes multiple lines, or when Enter key is pressed, for example. 例如,当用户复制粘贴多行或按下Enter键时,可能会发生这种情况。 If you do not want that to happen, you need to take extra care to ignore \\n . 如果您不希望这种情况发生,您需要格外小心忽略\\n For example: 例如:

#include <stdio.h>

int main() { 
    char c;
    printf("Enter any character\n");

    for (c=0; c<=122; c++)
    {
        scanf("%c", &c);
        if (c == '\n')
            break; /* Or perhaps continue? Depends on what you actually want. */
        printf("%d",c);
    }
    return 0;
}

Also, note that different systems may have different conventions as for what newline actually is. 另请注意,不同的系统可能有不同的约定,实际上是换行符。 On UNIX, it is \\n character only, on Windows, it might be a combination or \\r and \\n . 在UNIX上,它只是\\n字符,在Windows上,它可能是组合或\\r\\n So if you want to make your program portable, this needs to be taken into account. 因此,如果您想让您的程序可移植,则需要将其考虑在内。 You can either do it yourself, or use some other library (GNU getline comes to mind). 您可以自己做,也可以使用其他库(想到GNU getline )。 You can read more about newline here . 您可以在此处阅读有关换行的更多信息。

You may want to exclude some chars from the output and not only '\\n', in that case you can try something like this: 您可能希望从输出中排除一些字符,而不仅仅是'\\ n',在这种情况下,您可以尝试这样的事情:

#include <stdio.h>
int isEndingChar(char c) {
   char terminators[3] = {'\r','\t','\n'}
   int n;
   for( n=0; n<3; n++ ) {
      if( terminators[i]==c )
         return 1;
   }
   return 0;
}

int main() { 
   char c;
   printf("Enter any character\n");
   for (c=0; c<=122; c++)
   {
      scanf("%c", &c);
      if( isEndingChar( c ) )
        break;
      printf("%d",c);
   }
   return 0;
}

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

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