JLWK
JLWK

Reputation: 65

Swapping variables and printing them out in C

I've written the code to accept a user y/n input, however upon running the code, the console just print out random and inconsistent characters.

    int main()
{
    char var1 = "A";
    char var2 = "$";
    char user_answer;

    printf("Do you wanna swap var1 and var2? y/n \n ");
    scanf("%c", &user_answer);

    if (user_answer == 'y')
    {
        var1 = "$";
        var2 = "A";
        printf("var1 is now: %c", &var1, "\n", "var2 is now: %c", &var2);
    }
    else
    {
        exit(0);
    }

    return 0;
}

I have been debugging this for hours. Any corrections of what went wrong? Thanks!

Upvotes: 0

Views: 85

Answers (3)

P.A
P.A

Reputation: 821

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

int main()
{
    char var1 = 'A';
    char var2 = '$';
    char user_answer;

    printf("Do you wanna swap var1 and var2? y/n \n ");
    scanf("%c", &user_answer);

    if (user_answer == 'y')
    {
        var1 = '$';
        var2 = 'A';
        printf("var1 is now: %c\n",var1);
        printf("var2 is now: %c\n",var2);

    }
    else
    {
        exit(0);
    }

    return 0;
}

Upvotes: 0

nbro
nbro

Reputation: 15847

The essential problem with your code is that you're implicitly converting a pointer to an integer with the following code:

char var1 = "A";
char var2 = "$";
...

To initialize a character you should use single quotes instead of double ones. The C compiler does not give you an error unfortunately because it actually interprets "A" as a pointer to a character which he converts to an int and since characters in C are integers no error is really produced.

By the way, you should have received a warning of the form (compiled with gcc 5.3.0):

jdoodle.c:2:17: warning: initialization makes integer from pointer without a cast [-Wint-conversion]
     char var1 = "A";

If you want to read just a single char, you probably want to use the getchar function, instead of scanf.

Upvotes: 1

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

First of all char is not a string type, it's an integer1 type with size 1 byte that is useful to store a single character, so yuo need to change

char var1 = "A";

to2,

const char *var1 = "A";

the same with var2, and then you are using printf() wrong, try

printf("var1 is now: %s\nvar2 is now: %s\n", var1, var2);

And READ THE DOCUMENTATION


1It's signed in principle.

2Use const because it points to a string literal which is by definition, read only.

Upvotes: 1

Related Questions