1.scanf("%s",str)和gets(str)
scanf("%s",str)和gets(str)均可用于輸入字符串到字符數(shù)組變量str,但scanf("%s",str)只讀到輸入字符的空格或回車處,而gets(str)讀到回車處結(jié)束,所以當句子中單詞由空格分開時要用后者來輸入,如下圖所示:
需要強調(diào)一點,scanf("%s",str)在遇到'/n'(回車)或' '(空格)時輸入結(jié)束,但'/n'(回車)或' '(空格)停留在出入緩沖區(qū),如處理不慎會影響下面的輸入;gets(str)遇到'/n'(回車)時輸入結(jié)束,但'/n'(回車)已被替換為'/0',存儲于字符串中,輸入緩沖中沒有遺留的'/n'(回車),不會影響后續(xù)的輸入。測試程序的代碼為:
#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
//freopen("http://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())!='/n'&&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())!='/n'&&ch!=EOF);
gets(str);
cout<<"用gets(str)輸入的字符串為:"<<str<<endl;
return 0;
}
其中while((ch=getchar())!='/n'&&ch!=EOF);是處理輸入緩存中的遺留的辦法;fflush(stdin)方法對某些編譯器不適用,不是標準C支持的函數(shù)。
2、printf(“%s”,str)和puts(str)
先看如下代碼:
#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
//freopen("http://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;
}
從運行結(jié)果可以看出,printf(“%s”,str)和puts(str)均是輸出到'/0'結(jié)束,遇到空格不停,但puts(str)會在結(jié)尾輸出'/n',printf(“%s”,str)不會換行。printf(“%s/n”,str)可以替換puts(str)。
完。
新聞熱點
疑難解答
圖片精選