Home > Software design >  I am trying to create a C program where it will keep asking the user for a string of text and then p
I am trying to create a C program where it will keep asking the user for a string of text and then p

Time:06-26

I am fairly new at programming and I want to experiment with file pointers. I did my best into trying to find ways to have the user infinitely enter strings and the program will keep inputting it into the file. But I still cannot figure out how. Here is my code :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>




int main()
{
    char text[100];

    FILE *output = fopen("output.txt", "a");
    if (output == NULL)
    {
        printf("Could not open file\n");
        return 1;
    }


    while (1)
    {
        //Asks the user for input
        printf("Enter Text: \n");
        scanf("%[^\n]", text);

        //if user puts the string "end", it will stop asking for input
        if (strcmp(text, "end") != 0)
        {
        //puts the user input into the file
        fprintf(output, "%s\n", text);
        }
        else
        {
            break;
        }
    }
    fclose(output);
}

But after I input 1 line of string, it just loops over and over until I manually break it. Any help would be appreciated

CodePudding user response:

Your code scanf("%[^\n]", text); reads everything until and excluding the newline into the buffer.
This succeeds for an initial "end" as input.
But that will leave a "\n" in input, which in turn makes all following inputs fail the scan, because they immediatly find the terminating "\n" and they remove nothing from input, not even that "\n".
Assuming that you can ignore leading whitespace, you can change to

scanf(" %[^\n]", text);

It will ignore all leading whitespace, including the problematic "\n" from the end of preceeding lines.

If you need to keep leading white space you need to more surgically scan the "\n" when you know that one is there, e.g. starting with the second scan and ignore it explicitly.

  • Related