1

Trying to create a simple C char to ASCII convertor

But the result print "10" after each printf.

Any Ideas to resolve that?

Compiler: mingw64/gcc

Source:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main() {
    char argc;
    printf("Enter for ASCII: ");
    do {
        scanf("%c", &argc);
        printf("%d\n", argc);
    } while (argc != 'Z');
}

Output:

$ ./ascii.exe 
Enter for ASCII: A 
65
10
S
83
10
D
68
10
V
86
10
X
88
10
Z
90
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
ycohui
  • 66
  • 7
  • 1
    The `10` is the decimal value for the newline character `'\n'`. It depends on what you want to do, but adding a space to your format string probably works: `scanf(" %c", &argc);` – Cheatah Nov 21 '21 at 10:14

1 Answers1

2

scanf with the format string "%c" reads all characters including white space characters as for example the new line character '\n' that corresponds to the pressed key Enter. To skip white space characters you can either prepend the format string with a space like

    scanf( " %c", &argc);
           ^^^^^

The C Standard 7.21.6.2 The fscanf function

5 A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read.

Or you can ignore it in the loop the following way

do {
    scanf("%c", &argc);
    if ( argc != '\n' ) printf("%d\n", argc);
} while (argc != 'Z');
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335