0

ユーザー入力の文字列を受け取り、それをファイルに書き込もうとしています。ただし、何をしても、出力には常に文字列からスペースが削除されます。

gets()/を使用する全体的な目的はputs()、改行文字に遭遇するまで文字列内のすべての文字を読み取り/出力することだと思いました。

誰かが私が間違っていることを教えてもらえますか??

int main (void){
    char userInput[100];
    char filename[50];
    FILE *cfPtr;

    printf("Enter name of file to open: ");
    scanf("%s", &filename);

    cfPtr = fopen(filename, "a+");

    printf("Enter text to add to file: \n");
    fgets(userInput, 100, stdin);

    while (strcmp( userInput, "0") != 0) {
        fputs( userInput, cfPtr);
        fgets(userInput, 100, stdin);
    } // end while

    fclose( cfPtr );

    system("pause");
} // end main
4

3 に答える 3

0

これは g++ と Linux で動作します。

int main (void){  
  char userInput[100];  
  char filename[50];  
  FILE *cfPtr;

  printf("Enter name of file to open: ");  
  scanf("%s\n", filename);

  cfPtr = fopen(filename, "a+");

  printf("Enter text to add to file: \n");  
  fgets(userInput, 100, stdin);

  while (strcmp( userInput, "0\n") != 0) {  
      fputs( userInput, cfPtr);  
      fgets(userInput, 100, stdin);  
  } // end while

  fclose( cfPtr );

  //system("pause");  
} // end main
于 2013-07-23T20:56:30.867 に答える