Home > Net >  C ascii converter printf Extra integer
C ascii converter printf Extra integer

Time:11-22

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

CodePudding user response:

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');
  • Related