Convert string to const * char for ofstream.

So I am just playing around, changing things to see what happens when I do (I learn this way). I know this isn't how one should do it, but I wondered how I could get this to work. This is my third or so try at what I want. I am hoping to be able to use ofstream.write to write a string to a file one letter at a time.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <fstream>
using namespace std;
int main()

{
    const string S = "Funky";
    const char * c = &S[0];
    ofstream output("Output.txt");

    if (!output.is_open())
    {
	cout << "Cannot open that file." << endl;
	return 0;
    }

    for (int k=0; k<S.length(); k++)
    {
	output.write(c,S.length());  // Doesn't work.
    }

    output.close();
}
Last edited on
Thanks quirkyusername, but doing:

const char * c = S.c_str();

is basically (as far as the result in the text file) the same as what I did, i.e.,

const char * c = &S[0];


The result is the same, 5 copies of the word "Funky" in the text file. The problem (AFAIK) is that output.write wants a const * char, so in order to do each letter one at a time, I need each element of c to be a const * char. If I am wrong, please tell me how! Thanks again.
Last edited on
I figured it out. Remember I was just playing around trying to learn by doing, so as expected, this isn't pretty. If anyone knows of a more elegant way to start with a string object and write to a file using "write" one letter at a time, please post it here. Thanks.

Here is what I came up with.




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <fstream>
using namespace std;
int main()

{
    string S = "Funky";
    ofstream output("Output.txt");

    if (!output.is_open())
    {
	cout << "Cannot open that file." << endl;
	return 0;
    }

    for (int k=0; k<S.length(); k++)
    {
	const char * d = &S[k];
	output.write(d,1);
    }

    output.close();
}
Last edited on
Topic archived. No new replies allowed.