Home > Blockchain >  How to save the output of printf() as a variable in c?
How to save the output of printf() as a variable in c?

Time:10-04

I've code c for a very short time and have a problem, which I can't solve. I want to save a string with variables

"order_%d: <a href=\"order_%d\"><button>ON</button></a><br />", x, x    //x = 1,2,3,4...

into a variable named content. But all my attempts were useless. The code, which fits the most to my planned result is:

#include <stdio.h>
#include <stdbool.h>
bool order_state = false;

int orders_cond (int x, bool state){
    if (!state){
        printf("order_%d: <a href=\"order_%d\"><button>ON</button></a><br />", x, x);
    }
    else {
        printf("Error");
    }
}
int main(){ 
    int x;
    printf("Enter a number:\n");
    scanf("%d", &x);
    orders_cond(x, order_state);
    return (0);
}

The output of this code is:

Enter a number:
8
order_8: <a href="order_8"><button>ON</button></a><br />

My idea was to save the last line of the output into a variable, but I don't know, how to do that.

Please explain me, how I can do this or if there's another method, how does this method work.

CodePudding user response:

You could use sprintf to print the formatted string to your variable, then use printf to print the contents to the screen:

char contents[STRING_LEN] = {0};
sprintf(contents, "order_%d: <a href=\"order_%d\"><button>ON</button></a><br />", x, x);
printf("%s", contents);

The sprintf statement puts the formatted string into array contents and printf prints the contents of contents to the screen.

You will have to make sure that the array contents is large enough to hold the entire string, otherwise you will have overflow.

If you want to avoid overflow, you could use snprintf and replace the sprintf statement with:

snprintf(contents, STRING_LEN, "order_%d: <a href=\"order_%d\"><button>ON</button></a><br />", x, x);

An example may be found here: https://www.educative.io/edpresso/storing-formatted-data-using-sprintf-in-c

CodePudding user response:

You probably want something like this:

#include <stdio.h>
#include <stdbool.h>

bool order_state = false;

int orders_cond(int x, bool state, char *outputstring) {
  if (!state) {
    sprintf(outputstring, "order_%d: <a href=\"order_%d\"><button>ON</button></a><br />", x, x);
  }
  else {
    sprintf(outputstring, "Error");
  }

  return 0;   // you probably need to return something meaningful here
              // or have   void orders_cond(...
}

int main() {
  int x;
  printf("Enter a number:\n");
  scanf("%d", &x);

  char outputstring[100];
  orders_cond(x, order_state, outputstring);

  printf("Content of outputstring: \"%s\"\n", outputstring);

  return 0;   // Bonus: don't put expressions after return between (), it's unusual and useless.
}

Disclaimer: there is still room for improvement, for example by using snprintf in order to prevent buffer overflows.

  • Related