I am beginner for programming.I referred books of C programming,but i am confused.
1.) What’s the difference betweent printf and gets?
I believe gets is simpler and doesn’t have any formats?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
printf
The printf function writes a formatted string to the standard output. A formatted string is the result of replacing placeholders with their values. This sounds a little complicated but it will become very clear with an example:
Here
%sand%dare the placeholders, that are substituted with the first and second argument. You should read on the man page (linked above) the list of placeholders and their options, but the ones you’ll run into most often are %d (a number) and %s (a string).Making sure that the placeholder arguments match their type is extremely important. For example, the following code will result in undefined behavior (meaning that anything can happen: the program may crash, it may work, it may corrupt data, etc):
Unfortunately in C there is no way to avoid these relatively common mistakes.
gets
The gets function is used for a completely different purpose: it reads a string from the standard input.
For example:
This simple program will ask the user for a name and save what he or she types into
name.However, gets() should NEVER be used. It will open your application and the system it runs on to security vulnerabilities.
Quoting from the man page:
Explained in a more simple way the problem is that if the variable you give gets (
namein this case) is not big enough to hold what the user types a buffer overflow will occur, which is,getswill write past the end of the variable. This is undefined behavior and on some systems it will allow execution of arbitrary code by the attacker.Since the variable must have a finite, static size and you can’t set a limit of the amount of characters the user can type as the input,
gets()is never secure and should never be used. It exists only for historical reasons.As the manual suggested, you should use fgets instead. It has the same purpose as
getsbut has asizeargument that specifies the size of the variable:So, the program above would become: