Search code examples
ccompiler-errorsprintfscanf

How to print a statement which includes a scanned character and an integer in C?


This is the code that I am trying to run -

#include <stdio.h>
int main()
{
char a;
int b;
printf("Name of Prisoner\n");
scanf("%c" ,a);

printf("How many years in jail as stated by the court?\n");
scanf("%d", b);

printf("Prisoner "a" goes to jail for "b" years\n"a,b);

return 0;    

}

This is the Error shown -

P.c: In function 'main':
P.c:14:23: error: expected ')' before 'a'
printf("Prisoner "a" goes to jail for "b" years\n"a,b);
                   ^

As you can see I am at a very beginner level at C or any programming language. I want to collect the name of the prisoner and the years of prison sentenced to him and simply print a statement which includes the data collected. But it is not being compiled. The error is given. I am pretty sure it's a very small and simple fix but I am trying to run a little bit ahead of my classes and don't have any personal guide or teacher with me. Can anyone please educate me on this issue?


Solution

  • Kindly note that the statement printf("Prisoner "a" goes to jail for "b" years\n"a,b); contains an error, indicative of a common mistake made by beginner programmers. I encourage you to thoroughly review the error message provided, aiming to comprehend its nuances and rectify similar errors in the future. Additionally, investing time in studying format specifiers in C will enhance your understanding of proper usage in print and scan statements, contributing to more robust and error-free code.Websites like Format specifiers in C helps you to move on from the beginner level.

    #include <stdio.h>
    int main()
        {
            char a[10]; //Use character array for declaring sequence of character
            int b;
            printf("Name of Prisoner\n");
            scanf("%s" ,a);
    
            printf("How many years in jail as stated by the court?\n");
            scanf("%d", &b);
    
            printf("Prisoner %s goes to jail for %d years\n",a,b);
    
            return 0;    
    
         }
    

    output:

    Name of Prisoner
    Mike
    How many years in jail as stated by the court?
    4
    Prisoner Mike goes to jail for 4 years
    

    And while learning about arrays, Additionally go through the similar of Arrays and pointers C pointers and arrays