Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C ascii converter printf Extra integer

Trying to create a simple C char to ASCII convertor

But the result print "10" after each printf.

Any Ideas to resolve that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading