C language Input Statements scanf and Fgets Linux

Source: Internet
Author: User
Tags stdin

1. An example of testing using scanf:

#include "stdio.h"

#include "string.h"

int main ()

{

Char name[10];

scanf ("%s", name);

puts (name);

return 0;

}

Compile and invoke the following:

Can see the second time, due to the input string length, resulting in abort

2, the same example of a fgets:

#include "stdio.h"

#include "string.h"

int main ()

{

Char name[10];

Fgets (name, ten, stdin);

puts (name);

return 0;

}

Compile and invoke the following:

There is no case of abort like scanf, but a truncation of the string

3. Compare scanf and Fgets:

A) scanf does not restrict user input, resulting in the abort of the above test example

Fgets restricts the user's input, and then truncates the string, avoiding abort, but setting a buffer length value

b) scanf can be used such as scanf ("%d/%d", &x, &y) in such a way that the user only needs to enter 1/3 to get the values of x and Y respectively:

#include "stdio.h"

int main ()

{

int x;

int y;

scanf ("%d/%d", &x, &y);

printf ("x value:%d, y value:%d\n", x, y);

return 0;

}

But fgets, in any case, can only read one variable at a time, and it can only be a string (after all, it's str!). ), as in the following form, compilation is not a pass:

#include "stdio.h"

int main ()

{

int x;

Fgets (x, sizeof (x), stdin);

printf ("x Value:%d", x);

return 0;

}

c) spaces in the string

When scanf receives a string with%s, it stops when it encounters a space. If you want to enter multiple words, you need to call scanf () multiple times

Fgets () directly receives spaces in a string

4. Summary

Due to some of the differences mentioned in 3, be aware of the situation when using scanf () and fgets ().

Reproduced in: 19540153

C language Input Statements scanf and Fgets Linux

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.