-1

Good day everyone. My code is working fine until I have to use a variable as value for a header. Wanna know on how to use a variable as value in header. I have searched ton already but couldnt find an example on the correct format on how to use a variable as part of a header. This is the part of my codes(the codes are working well without the variable as key, but when the need to use comes, the code doesnt return anything, just blank window without any error.)

// my imports and write callback here


int seconds;

int main()

{

    time_t seconds;
    seconds = time(NULL);
    cout << "Time: " << seconds;


    CURL* curl = curl_easy_init();
    struct curl_slist* header = NULL;
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "mytestwebsite.com");
        header = curl_slist_append(header, "Timestamp: " + seconds); // THIS seconds variable here.
        // some other headers to append
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header);
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);



        cout << "Response 1: " << seconds;

        curl_easy_cleanup(curl);
    }
    return 0;
{

Hoping to hear from my helpful brothers! Thanks in advance!

273K
  • 29,503
  • 10
  • 41
  • 64
Work Work
  • 5
  • 3
  • Do you know how to use `std::ostringstream`, or `std::to_string`, or `std::to_chars`? Either one can be used here. – Sam Varshavchik Aug 02 '22 at 10:54
  • `"Timestamp: " + seconds` would result in some serious out of bounds access. That becomes a `char*` that points at the `'T'` in `"Timestamp"` + `seconds` `char`s – Ted Lyngmo Aug 02 '22 at 11:01

1 Answers1

1

The reason for the problem you're having is a little long-winded (array to pointer decay, pointer arithmetic, etc.), I'll only tell you how to solve the problem...

You need to convert the value of seconds to a string and then concatenate the strings to create the key-value string.

You can do that with the help of the std::to_string function:

std::string seconds_string = "Timestamp: " + std::to_string(seconds);

Then use seconds_string for the header:

header = curl_slist_append(header, seconds_string.c_str());  // c_str() to get a C-style string pointer
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621