简体   繁体   中英

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

ex: input: ab; output:9798

This is my code but there's a 10 at the end of it

#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. In other words, you process \\n character as part of the input. This can happen when user copy-pastes multiple lines, or when Enter key is pressed, for example. If you do not want that to happen, you need to take extra care to ignore \\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 . 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). 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:

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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