How to print two strings on the same line in c using printf

86 views Asked by At

I am trying to print the out put of name and phone. Keeps showing this two errors in terminal

format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’

and

format ‘%s’ expects argument of type ‘char *’, but argument 3 has type ‘int’

my code:

int main(void)
{
    char name,phone;
    int age;


    printf("Kindly input your name, age and phone number");
    scanf("%s %s %d", &name, &phone, &age);
    printf("%s %s %d\n", name, phone, age);
    return 0;
}
2

There are 2 answers

0
Vlad from Moscow On

The error message means that in this call of printf

printf("%s %s %d\n", name, phone, age);

argument expressions name and phone having the type char are promoted to the type int and there is used the conversion specification %s designed to output strings instead of integers.

Instead of declaring these variables as having the scalar type char you need to declare them as having a character array type to be able to store strings.

And you should change the prompt

printf("Kindly input your name, age and phone number");

like

printf("Kindly input your name, phone number and age: ");

For example

char name[20], phone[20];
int age;


printf("Kindly input your name, phone number and age: ");
scanf("%19s %19s %d", name, phone, &age);
printf("%s %s %d\n", name, phone, age);
1
Jib On

Your sample code is likely to fault .. Actually, you are storing an array of characters (string) into a single char memory location. You should rather do this:

/* Note the array definition `[]`.
 * Note that 32 is an arbitrary length, change it as per your needs.
 */
char name[32], phone[32];

Then, as an array is already a pointer to memory location, you can use it without the &.

scanf("%31s %31s %d", name, phone, &age);

EDIT: as suggested in comment, you can restrict the maximum input size. Knowing a string is NULL-terminated, in the example the maximum total string length becomes 31.