Justin D.
Justin D.

Reputation: 4976

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). 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.

#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...

Upvotes: 0

Views: 10015

Answers (4)

LihO
LihO

Reputation: 42133

" I am trying to scan a user input (ascii character) as an integer, and show the ascii code for the entered character"

What you should do is exact opposite. You should read a character and display it as an integer, i.e.:

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

input: a, output: 97


Also note that while(character != 999) isn't very lucky choice for a terminating condition of your loop. Checking the return value of scanf to determine whether the reading of character was successful might be more reasonable here:

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

Upvotes: 4

PersianGulf
PersianGulf

Reputation: 2885

change to :

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

However , What your condition speciftied 999?

Upvotes: 0

vacehcto
vacehcto

Reputation: 76

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. Change the "%d" to "%c" and it should work.

Upvotes: 0

sukhvir
sukhvir

Reputation: 5575

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

Upvotes: 1

Related Questions