Enter text and save to file

前端 未结 1 1123
终归单人心
终归单人心 2021-01-25 23:38

The following function creates a new text file and allows the user to input text to be saved to the file. The main issues that I\'m having troubles fixing is 1)allowing spaces b

相关标签:
1条回答
  • 2021-01-25 23:48

    Use fgets() instead of scanf() to get the input text from the user.

    To do so replace this line

    scanf("%s", c); 
    

    with the following code:

    if (NULL != fgets(c, sizeof(c), stdin))
    {
      fprintf(pf, "%s", c);
    }
    else
    {
      if (0 != ferror(stdin))
      {
        fprintf(stderr, "An error occured while reading from stdin\n");
      }
      else
      {
        fprintf(stderr, "EOF was reached while trying to read from stdin\n");
      }
    }
    

    To allow the user to read in more then one line put a loop around the code above. Doing so you need to define a condition which tells the program to stop looping:

    The following example stops reading in lines when entering a single dot "." and pressing return:

    do
    {
      if (NULL != fgets(c, sizeof(c), stdin))
      {
        if (0 == strcmp(c, ".\n")) /* Might be necessary to use ".\r\n" if on windows. */
        {
          break;
        }
    
        fprintf(pf, "%s", c);
      }
      else
      {
        if (0 != ferror(stdin))
        {
          fprintf(stderr, "An error occured while reading from stdin\n");
        }
        else
        {
          fprintf(stderr, "EOF was reached while trying to read from stdin\n");
        }
    
        break;
      }
    } while (1);
    
    0 讨论(0)
提交回复
热议问题