The difference between scanf of printf of and gets of puts of when inputting and outputting strings

  • 2020-04-01 21:33:06
  • OfStack

1. The scanf (" % s ", STR) and gets (STR)

Scanf ("%s", STR) and gets(STR) can both be used to enter a string into a character array variable STR, but scanf("%s", STR) reads only the space or carriage return of the input character, and gets(STR) reads to the end of the carriage return, so use the latter when the word in the sentence is separated by Spaces, as shown below:

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201302/2013228163036556.png" >

It is important to note that scanf("%s", STR) ends when it encounters '\n' (enter) or ' '(space), but '\n' (enter) or' '(space) stays in and out of the buffer. The input ends when gets(STR) encounters '\n' (enter), but '\n' (enter) has been replaced with '\0', stored in a string, and there is no '\n' (enter) left in the input buffer, which does not affect subsequent input. The code of the test program is:


View Code 
#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
  //freopen("//home//jack//jack.txt","r",stdin);
  char str[80];
  char ch;
  cout<<"1 Please enter a string without Spaces :"<<endl;
  scanf("%s",str);
  cout<<" with scanf("%s",str) The input string is :"<<str<<endl;
  cout<<" Enter it again for comparison :"<<endl;
  while((ch=getchar())!='n'&&ch!=EOF);
  gets(str);
  cout<<" with gets(str) The input string is :"<<str<<endl;
  cout<<"2 Please enter a string with Spaces :"<<endl;
  scanf("%s",str);
  cout<<" with scanf("%s",str) The input string is :"<<str<<endl;
  cout<<" Enter it again for comparison :"<<endl;
  while((ch=getchar())!='n'&&ch!=EOF);
  gets(str);
  cout<<" with gets(str) The input string is :"<<str<<endl;
  return 0;
}

While ((ch = getchar ())! && ch = '\ n'! = (EOF); Is a way of dealing with the legacy in the input cache; The fflush(stdin) method is not suitable for some compilers and is not a function supported by standard C.

2. Printf (" %s ", STR) and puts(STR)

First look at the following code:


View Code 
#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
  //freopen("//home//jack//jack.txt","r",stdin);
  char str1[80]="hello";
  cout<<" with printf("%s",str1) The output string is: ";
  printf("%s",str1);
  cout<<" with puts(str1) The output string is : ";
  puts(str1);
  char str2[80]="hello world";
  cout<<" with printf("%s",str2) The output string is : ";
  printf("%s",str2);
  cout<<" with puts(str2) The output string is : ";
  puts(str2);
  return 0;
}

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201302/2013228163241651.png" >

As you can see from the results of the run, printf(' %s', STR) and puts(STR) are both output to the end of '\0' and no Spaces are encountered, but puts(STR) outputs '\n' at the end and printf(' %s', STR) does not wrap. Printf (" %s\n ", STR) can replace puts(STR).

To the end.


Related articles: