Pass the contents of the stringstream to a function that takes char * as an argument

I have a function to write ppm files (image format) to disk. It takes the file name as a char * array. In my main function, I compiled a file name using a string stream and an <operator. Then I want to pass the results of this to my ppm function. I saw this discussed elsewhere, often with very confusing methods (many of the transition steps).

What I did is shown in the code below, and the tricky part that others usually take many steps with temporary variables is (char*) (PPM_file_name.str().data()). To do this, extract the string from stringstream PPM_file_name using .str (), and then get a pointer to its actual contents using .data () (this is const char *), and then apply it to the regular (char *). A more complete example is below.

I found the following to work well so far, but it makes me restless, because usually when other people did something seemingly more confusing, this is because it is a safer way to do this. So, can someone tell me that what I'm doing here is safe, and also how portable is it?

Thank.

#include <iostream>
#include <sstream>
#include <stdio.h>
#include <string>
using namespace std;

int main(int argc, char *argv[]){

    // String stream to hold the file name so I can create it from a series of other variable
    stringstream PPM_file_name; 

    // ... a bunch of other code where int ccd_num and string cur_id_str are created and initialized

    // Assemble the file name
    PPM_file_name << "ccd" << ccd_num << "_" << cur_id_str << ".ppm";

    // From PPM_file_name, extract its string, then the const char* pointer to that string data, then cast that to char*
    write_ppm((char*)(PPM_file_name.str().data()),"ladybug_vidcapture.cpp",rgb_images[ccd_num],width,height);                   

    return 0;
}
+3
6

, - const- . :

  • write_ppm , , const corrct

  • , , , const_cast

  • , std::vector & vec [0] ( vec )

+2

. , , , write_ppm:

write_ppm, const char *:

void write_ppm(const char *file_name, char *comment, unsigned char *image,int width,int height)

ppm_file_name :

write_ppm((PPM_file_name.str().c_str()),"A comment",rgb_images[ccd_num],width,height);

-, , , ? char write_ppm const? , . .

+3
  • PPM_file_name.str().c_str(), data() .

  • write_ppm() const char* (, ), ( ).

C-style cast ++, . const, , , const_cast<>. , , const_cast<> , const -, .

+1

, write_ppm , undefined. const_cast<char*> C-. c_str() data().

+1

Use c_str()instead data()( c_str()return a NULL-terminated character sequence).

0
source

Why not just use it const_cast<char *>(PPM_file_name.str().c_str())?

0
source

Source: https://habr.com/ru/post/1774348/


All Articles