wafwoof
wafwoof

Reputation: 35

How do I add user input to a void function?

I'm trying to make a program that asks for a string of text, then adds it to a log file of sorts. In its current form the code prints literally "%s".

int main()
{   
    char input[512];
    printf("input string: ");
    fgets(input, sizeof(input), stdin);
    putText("%s", input);
    printf("\ndone!\n");
    
    return 0;
}

void putText(char userText[])
{
    FILE * log;
    log = fopen("log1.txt", "a+"); //a+ for append + create.
    fprintf(log, "%s\n", userText);
    //fclose(log);
        
}

Also I'm pretty new to all this, although that's probably pretty obvious from where you all are sitting.

Upvotes: 0

Views: 1312

Answers (1)

zgyarmati
zgyarmati

Reputation: 1153

If you want to pass printf-like parameters to your own function, you need to use a function with variadic arguments. Here is a simple example:

int putText(const char *format, ...)
{
    va_list args;
    va_start(args, format);
    FILE * log;
    log = fopen("log1.txt", "a+"); //a+ for append + create.
    fprintf(log, format, args);
    va_end(args);
}

For the corresponding documentation, see https://www.gnu.org/software/libc/manual/html_node/Variadic-Functions.html

Upvotes: 2

Related Questions