出力文字列を入力する時scanf()、printf()とgets()、puts()の違いは簡単です。


1.scanf(「%s」、str)とgets(str)
scanf(「%s」、str)とgets(str)は文字列を文字配列変数strに入力するのに使用できますが、scanf(「%s」、str)は入力文字の空欄または回車のところに読み取り専用です。gets(str)は回車所で読み終わります。だから、文の中の単語が空欄で区切られている時は後者で入力します。

ちょっと強調したいのですが、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=getch)!='&ch!=EOF)入力キャッシュに残したものを処理する方法です。fflush(stdin)方法はいくつかのコンパイラには適用されません。標準Cでサポートされている関数ではありません。
2、printf(「%s」、str)とput(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)とput(str)はいずれも'0'に出力されて終わり、スペースに遭遇しましたが、put(str)は最後に'を出力します。printf("%s",str)は改行しません。printf(「%s」、str)はputsを置き換えることができます。
終わります。