Helper
Helper

Reputation: 11

Weird thing happening with output in C

So the problem is that I have to print a value(decimal, octal, hex) between two characters.

The code is:

#include <stdio.h>

int main (void) {
    char a, b;
    int z, temp;
    printf("Enter first character: ");
    scanf("%s", &a);
    printf("Enter second character: ");
    scanf("%s", &b);
    if (a>b){
        temp = a;
        a = b;
        b = temp;

    }

    printf("ASCII code difference: %d", b-a);
    for (int i = a; i <=b; i++){
        printf("\n%c %d %o %X", i, i, i, i);
    }
    return 0;
}

And the output:

Enter first character: a
Enter second character: z
ASCII code difference: 122
 0 0 0
 1 1 1
 2 2 2
 3 3 3
 4 4 4
........
y 121 171 79
z 122 172 7A

But it should be:

Enter first character: a
Enter second character: z
ASCII code difference: 122
a 97 141 61
b 98 142 62
c 99 143 63
........
y 121 171 79
z 122 172 7A

Is there anything I can do with it? I compiled it with gcc in debian wsl2. Thanks in advance!

Upvotes: 1

Views: 81

Answers (2)

Farooq Seedat
Farooq Seedat

Reputation: 189

The problem is that you are using %s that is used for reading strings instead of %c (reads a single character from the stream). Thus, you need to use %c that reads a single character from the stream, but it leaves a new line character in the stream, so you need to use %c that ignores any leading whitespace character left in a stream from the last input.

#include <stdio.h>

int main (void) {
    char a, b;

    printf("Enter first character: ");
    scanf("%c", &a);

    printf("Enter second character: ");
    scanf(" %c", &b);

    if (a > b) {
        char temp = a;
        a = b;
        b = temp;
    }

    printf("ASCII code difference: %d", b - a);

    for (int i = a; i <= b; i++)
        printf("\n%c %d %o %X", i, i, i, i);

    return 0;
}

Upvotes: 4

yhyrcanus
yhyrcanus

Reputation: 3813

The second scanf is overwriting the first character with a null. For whatever reason, the compiler is putting 'b' in front of 'a'. As people in the comments mentioned, you're reading in a full string, when you want to be reading in a character. The token to do so is %c

The %c token alone doesn't skip leading whitespace, so if there's a newline in the input stream (from the time you typed in a) the scanf call will use the newline character immediately as the first character. To avoid this, use:

scanf(" %c", &b);

Upvotes: 1

Related Questions