1.scanf("%s",str)和gets(str)
scanf("%s",str)和gets(str)均可用於輸入字符串到字符數組變量str,但scanf("%s",str)匹配連續的一串非空白字符,遇到空格、tab或回車即結束,字符串前的空白字符沒有存入str,只表示輸入還未開始(感謝garbageMan的指正),而gets(str)讀到回車處結束,所以當句子中單詞由空格分開時要用后者來輸入,如下圖所示:
需要強調一點,scanf("%s",str)在遇到'\n'(回車)或' '(空格)時輸入結束,但'\n'(回車)或' '(空格)停留在出入緩沖區,如處理不慎會影響下面的輸入;gets(str)遇到'\n'(回車)時輸入結束,但'\n'(回車)已被替換為'\0',存儲於字符串中,輸入緩沖中沒有遺留的'\n'(回車),不會影響后續的輸入。測試程序的代碼為:

#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())!='\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支持的函數。
2、printf(“%s”,str)和puts(str)
先看如下代碼:

#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)會在結尾輸出'\n',printf(“%s”,str)不會換行。printf(“%s\n”,str)可以替換puts(str)。
完。