출력 문자열 을 입력 할 때 scanf(),printf()와 gets(),puts()의 차이 점 에 대한 간단 한 설명
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)를 교체 할 수 있 습 니 다.
끝나다
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
fscanf 함수다음은 csdn의 예입니다. 다음은 비슷한 몇 가지 함수 조작을 결합한 예를 제시한다.(파일의 일반 작업이기도 함) 1 쓰기 함수 실행 후: test.dat은 파일입니다. 내용: Your score of TEFLis...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.