The difference between scanf and gets getting strings

Source: Internet
Author: User
Tags include

In C, there are at least two functions that can be refactored to obtain a string:

1.SCANF ()

The header file: stdio.h

Syntax: scanf ("Format control string", variable address list);

When accepting a string: scanf ("%s", character array name or pointer);

2.gets ()

The header file: stdio.h

Syntax: Gets (character array name or pointer);

Both when the string is accepted:

1. Different points:

SCANF can not accept spaces, Tab tab, carriage return, etc.;

And gets can accept space, Tab tab and carriage return, etc.;

2. The same point:

The string is automatically added after the end of the acceptance.

Example 1:

#include <stdio.h>

main()

{

  char ch1[10],ch2[10];

  scanf("%s",ch1);

  gets(ch2);

}

In turn, type ASD space FG carriage return, ASD space FG return, then ch1= "asd\0", ch2= "ASD fg\0".

Example 2:

#include <stdio.h>

main()

{

  char ch1[10],ch2[10],c1,c2;

  scanf("%s",ch1);

  c1=getchar();

  gets(ch2);

  c2=getchar();

}

Type ASDFG carriage return, ASDFG carriage return, then ch1= "Asdfg\0", c1= ' \ n ', ch2= "Asdfg\0", the C2 needs to enter.

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.