Frage

I am trying to receive a string of user input and write it to a file. No matter what I do, however, the output always has the spaces removed from the string.

I thought that the whole purpose of using gets()/puts() was that it would read/output all of the characters in a string until it encounters a newline character.

Can somebody please tell me what I am doing wrong??

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
War es hilfreich?

Lösung

Can somebody please tell me what I am doing wrong??

First mistake that I can notice is in scanf, for string with %s you are using &:

scanf("%s", &filename);
            ^
            |
            remove it, undefined behavior

it should be just:

scanf("%s", filename);

your code will not work after this. I can't find any other syntax error so I believe this is the main bug in your code.

Andere Tipps

1) fgets() and fputs() won't remove any spaces from your string.

2) One potential "gotcha" is that fgets() WILL retain the "Enter" character(s), which you probably don't consider part of your string.

3) The problem in your code is probably with your "scanf()" - you should pass "filename" (which is an array), instead of "&filename" (which is duplicate redundant).

4) Even better, you might consider substituting "fgets()" for "scanf()".

IMHO...

PS: Here's a great link on using fgets() and friends:

http://beej.us/guide/bgc/output/html/multipage/gets.html

This runs under g++ and 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
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top