0

I have tried to print two integer values in the following printf() function:

printf("%s", "The quotient is %d with remainder %d", quo, rem);

My book says this should print

The quotient is 5 with remainder 1

(with quo being 11 and rem 1), but instead it prints

The quotient is %d with remainder %d

I am using gcc to compile and running Ubuntu 12.04 LTS (64 bit). Did I misread? Is it a compiler issue?

5 Answers 5

2

You are mistaken about how printf works. Only the first argument is parsed as a format string, and so %s is directly replaced with the given string, including %d's.

Correct form would be printf("The quotient is %d with remainder %d\n", quo, rem);

Sign up to request clarification or add additional context in comments.

Comments

1

Should be

printf("The quotient is %d with remainder %d", quo, rem);

The first argument is the pattern to print so you were printing

"The quotient is %d with remainder %d" as a plain string (%s).

Note that extra arguments in printf are just ignored so quo and rem are just ignored in your solution.

Comments

1

The first argument in printf() is the format string. when you do this

printf("%s", "The quotient is %d with remainder %d", quo, rem);

The format string is "%s" instead of "The quotient is %d with remainder %d".

You should do it like this

    printf("The quotient is %d with remainder %d", quo, rem);

Comments

1

My friend, try this

printf("The quotient is %d with remainder %d", quo, rem);

The first argument should be the format string. In your case it is wrongly "%s" when you wanted it to be "The quotient is %d with remainder %d"

Comments

0

You've got one too many format strings. You should be using:

printf("The quotient is %d with remainder %d\n", quo, rem);

Note the newline at the end. Without that, you may not see the output in a timely manner.

If the book has that mistake in it, and if it doesn't include the newlines, then I think you should probably decide to jettison the book and get a better one.

The output you got is what would be expected. The "%s" says 'take the next argument as a string and print it'; the extra arguments (quo and rem) are simply ignored.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.