Hi, I had a problem in printing a String class string to a file where I had declared:
string str1[10], str2[10];
And in str1[6] and str2[6] has the values which I wanna store the values by writing them to a txt file using the format:
// write to apsignal.txt
newfile= fopen("apsignal.txt","w");
if (newfile==NULL)
{
cout<<"Error opening apsignal.txt";
fclose(newfile);
return -1;
}
//Print to file with the signal strengths and corresponding clientIDs.
fprintf(newfile,"1" " %s" " %s", &str1[6], &str2[6] );
fclose(newfile);
however, it seems like it cannot print out the values in the txt file as it is a string class? So I was wondering if anyone can give me other alternatives to write the values into this text file?
Thanks! I had attached the relevant files and pls take a look at the apsignal.txt and you will know what I mean. Thanks for any help!
|
Ambitious contributor
|
|
| 31Jan2008,16:49 | #2 |
|
Well if you're going to continue to use the C API in a C++ program (I don't recommend it), then it would be
fprintf(newfile,"1" " %s" " %s", str1[6].c_str(), str2[6].c_str() ); |
|
Light Poster
|
|
| 11Feb2008,15:38 | #3 |
|
Sorry for the late reply...well...I've followed the way u coded by changing the fprintf to fprintf (newfile, "Test: %s %s\n", str1.c_str(), str2.c_str()); but it doesn't seem to work. Is there anything I need to import or I've left it out?
|
|
Newbie Member
|
|
| 11Feb2008,20:16 | #4 |
|
I Download your attached file but I found nothing in them except some garbage text.
Anyway Check This code Code:
#include <iostream>
#include <cstdlib>
#include <cctype>
#include <fstream>
#include <cstdio>
using namespace std;
int main()
{
string str[4]={"abc","def","ghi","jkl"};
/* c++ code
fstream f;
f.open("abc.txt",ios::out);
if(!f)
{
cout<<"Cannot Open File";
return 0;
}
f<<str[2];
f.close();
f.open("abc.txt",ios::in);
if(!f)
{
cout<<"Cannot Open File";
return 0;
}
f>>str[1];
cout<<str[1];
f.close();
*/
// C Code
FILE *fp;
fp = fopen("abc.txt","w");
if(fp==NULL)
{
cout<<"Cannot Open File";
return 0;
}
fprintf(fp,"%s",str[2].c_str());
fclose(fp);
return 0;
}
Quote:
The %s argument requires a c-styled string, but you've passed it an actual std::string object. [/quote] Check my above code in c++ code is working fine. Even if you are using %s then use c_str() function to convert it into const char *. Quote:
You can more read about POD in this link http://www.fnal.gov/docs/working-gro...x/doc/POD.html http://www.digitalfanatics.org/index...CompilerErrors Regards |
