good day everyone.. thx for reading..

this is my problem:
i want to use the write() function, in ofstream, to write strings into a file.. but write() requires parameters of const char pointer and streamsize...

for(unsigned i=0; i != questions.size(); i++)
	{
		qptr = &questions[i]; 		//vector element(string)
		tempfile.write(qptr, stringsize);
	}

do i really need to convert string to char first? any simpler way?

and,, any better idea than using write()??

thx..

Recommended Answers

All 5 Replies

If you're talking about std::strings you could use the c_str() method?

(I'm assuming "questions" is a vector of std::strings)

tempfile.write(questions[i].c_str(), questions[i].size());

But if tempfile is an ofstream, why not use the << operator?

ofstream tempfile("yourfilename_goes_here");
std::string foo = "bar";
tempfile << foo;

If you're talking about std::strings you could use the c_str() method?

(I'm assuming "questions" is a vector of std::strings)

tempfile.write(questions[i].c_str(), questions[i].size());

But if tempfile is an ofstream, why not use the << operator?

ofstream tempfile("yourfilename_goes_here");
std::string foo = "bar";
tempfile << foo;

ofstream,, so i can't use the 1st one..

my strings in the vectors have white spaces.. i think << stops on white spaces,, correct me if i'm wrong,, so can't use that one..

thx for help..

any other ideas?? i'll try to use write() for now,, converting my strings to char.. but any better ideas will help..

thx

i'll try to use write() for now,, converting my strings to char.. but any better ideas will help..

that's what option 1 does

#include <fstream>
#include <string>

int main(int argc, char *argv[]){
    std::string example = "Hello, world!\nHow are you?\n\tSuper thanks!";
    std::ofstream exfile("test.txt");
    
    if(!exfile.good()) return 0;
    exfile << example;
    
    exfile.close();
    return 0;
}

I see no whitespace problem...

Hello, world!
How are you?
	Super thanks!

Chris

ok,, thx for everything..

i thought << operator in ofstream is the same as << operator in cout... now i knew it doesn't stop at white spaces..

thx again!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.