how to do write to a file with a std::string
-
i've got this code FILE *tempf std::string s; arch=fopen(tempf,"r+"); cout <<"enter your name"; cin >>s; fprintf(arch,s); the last line doesn't compile. It says it can't convert from ...std::string.. to char * any ideas? thanks!
s.c_str() Maxwell Chen
-
i've got this code FILE *tempf std::string s; arch=fopen(tempf,"r+"); cout <<"enter your name"; cin >>s; fprintf(arch,s); the last line doesn't compile. It says it can't convert from ...std::string.. to char * any ideas? thanks!
#include <iostream>
#include <fstream>
#include <string>std::string s;
std::ofstream arch("filename");
std::cout << "enter your name: ";
std::getline(std::cin, s);arch << s;
Reading the name by using "cin >> s;" will stop at the first whitespace character, so if you want to read the entire line std::getline is just perfect. std::getline strips the newline characters from the end (both \r and \n). Personally find mixing C and C++ I/O a tad on the ugly side. I'm fully aware that it can be a necessity when incorporating C++ code in older apps, but for new code you might as well stick to the iostream library. I haven't included any error checking in the above code (those are the things we love to leave as an exercise for the reader, no?). All it needs more, really, is a check on whether the file was actually opened and good for writing. Hope this helps. -- Henrik Stuart (http://www.unprompted.com/hstuart/[^])
-
i've got this code FILE *tempf std::string s; arch=fopen(tempf,"r+"); cout <<"enter your name"; cin >>s; fprintf(arch,s); the last line doesn't compile. It says it can't convert from ...std::string.. to char * any ideas? thanks!
kfaday wrote: arch=fopen(tempf,"r+"); What is this? The first parameter to
fopen()
is aconst char*
filename, and the return value is aFILE*
. Something like:tempf = fopen("myfile.txt", "r+");
"The pointy end goes in the other man." - Antonio Banderas (Zorro, 1998)