출력 문자열 을 입력 할 때 scanf(),printf()와 gets(),puts()의 차이 점 에 대한 간단 한 설명

2984 단어 scanfprintfgetsputs
1.scanf("%s",str)와 gets(str)
scanf("%s",str)와 gets(str)는 문자 배열 변수 str 에 문자열 을 입력 하 는 데 사용 할 수 있 습 니 다.그러나 scanf("%s",str)는 입력 문자 의 빈 칸 이나 Enter 에 만 읽 고 gets(str)는 Enter 에서 끝 날 때 까지 읽 을 수 있 습 니 다.따라서 문장 에 있 는 단어 가 빈 칸 으로 나 눌 때 후자 로 입력 해 야 합 니 다.다음 그림 과 같 습 니 다.

한 가지 강조 가 필요 합 니 다.scanf('%s',str)는'(리 턴)또는'(빈 칸)을 만 났 을 때 입력 이 끝 났 지만'(리 턴)또는'(빈 칸)은 출입 버퍼 에 머 물 렀 습 니 다.만약 에 처리 하지 않 으 면 아래 의 입력 에 영향 을 줄 수 있 습 니 다.gets(str)가'(리 턴)를 만 났 을 때 입력 이 끝 났 지만'(리 턴)'은'\0'으로 바 뀌 었 습 니 다.문자열 에 저장 되 어 있 습 니 다.버퍼 에 남아 있 지 않 은'(리 턴)'을 입력 하면 후속 입력 에 영향 을 주지 않 습 니 다.테스트 프로그램의 코드 는:

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、 :"<<endl;
  scanf("%s",str);
  cout<<" scanf(\"%s\",str) :"<<str<<endl;
  cout<<" :"<<endl;
  while((ch=getchar())!='
'&&ch!=EOF);
  gets(str);
  cout<<" gets(str) :"<<str<<endl;
  cout<<"2、 :"<<endl;
  scanf("%s",str);
  cout<<" scanf(\"%s\",str) :"<<str<<endl;
  cout<<" :"<<endl;
  while((ch=getchar())!='
'&&ch!=EOF);
  gets(str);
  cout<<" gets(str) :"<<str<<endl;
  return 0;
}

그 중 while(ch=getchar()!='&&'ch!=EOF);입력 캐 시 에 남 겨 진 방법 처리 하기;fflush(stdin)방법 은 일부 컴 파일 러 에 적용 되 지 않 으 며 표준 C 가 지원 하 는 함수 가 아 닙 니 다.
2.printf("%s",str)와 puts(str)
먼저 다음 코드 를 보십시오.

View Code

#include<iostream>
#include<stdio.h>

using namespace std;

int main()
{
  //freopen("//home//jack//jack.txt","r",stdin);
  char str1[80]="hello";
  cout<<" printf(\"%s\",str1) :";
  printf("%s",str1);
  cout<<" puts(str1) : ";
  puts(str1);
  char str2[80]="hello world";
  cout<<" printf(\"%s\",str2) : ";
  printf("%s",str2);
  cout<<" puts(str2) : ";
  puts(str2);
  return 0;
}


실행 결 과 를 통 해 알 수 있 듯 이 printf('%s',str)와 puts(str)는 모두'\0'으로 출력 되 고 빈 칸 이 멈 추 지 않 지만 puts(str)는 끝 에 출력 됩 니 다',printf('%s',str)는 줄 을 바 꾸 지 않 습 니 다.printf("%s",str)는 puts(str)를 교체 할 수 있 습 니 다.
끝나다

좋은 웹페이지 즐겨찾기