Program output

M

Meenu

I can't understand the output of the following function:

main()
{
char str[]="part-time musicians are semiconductors";
int a=5;
printf(a>10?"%50s":"%s",str);
}
 
M

Meenu

I mean, if I make a=15 and do %20s instead of %50s, it prints the
entire statement rather than just first 20 chars
 
R

Rob Morris

Meenu said:
I mean, if I make a=15 and do %20s instead of %50s, it prints the
entire statement rather than just first 20 chars

Well, of course - %20s means print using at least 20 chars width. Consider:

#include <stdio.h>
int main (void)
{
char s[]="String.";
printf("s is '%20s'\n", s);
return 0;
}

This outputs:
s is ' String.'

Perhaps the OP was also confused about the ? operator. It's like an
abbreiviated if - then - else and can be useful in printf in forms like:
printf("There were %d error%s\n", errors, errors == 1 ? "" : "s" );
 
R

Rob Morris

Rob Morris wrote:
[Snip!]
Perhaps the OP was also confused about the ? operator. It's like an
abbreiviated if - then - else and can be useful in printf in forms like:
printf("There were %d error%s\n", errors, errors == 1 ? "" : "s" );
.... though one might wish to use slightly better grammar (D'oh!)
 
O

Old Wolf

Meenu said:
I mean, if I make a=15 and do %20s instead of %50s, it prints the
entire statement rather than just first 20 chars

It is considered polite on Usenet to quote parts of the
posts you are replying to, and then write your comments
after it, so that a reader can see what your post is about,
without having to refer to any other posts.

Since you didn't do this, I'll fill in: you were replying to
your own post which went:
I can't understand the output of the following function:
main()
{
char str[]="part-time musicians are semiconductors";
int a=5;
printf(a>10?"%50s":"%s",str);
}

The answer is that "%15s" means: print a MINIMUM of 15
characters (but possibly more).
To specify a maximum you could write:
"%.15s" -- print a MAXIMUM of 15 characters
"%10.20s" -- print a MINIMUM of 10 and a MAXIMUM of
20 chars (right-justified)
"%-10.20s" -- as above, but left-justified.

Also your program has some other errors:
- it must #include <stdio.h> because it calls printf
- it should return a value from main
- main should be declared as: int main(void)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,166
Messages
2,570,907
Members
47,448
Latest member
DeanaQ4445

Latest Threads

Top