string to char conversion

I need to get a word from a file, display it, and then change some letters of that word and then display it on the screen. The problem is on line 15, i hope its obvious what i want to do, i want to assign the word read from the file to my new variable 'word2', and then manipulate this variable. thanks in advanced

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main() {

	string word;
	ifstream inData("data.txt");
	
	if(inData.is_open())
    {
        getline (inData,word);
		cout << word <<endl;
		char word2[] = word;
		word2[0] = 'h';
		cout << word2 << endl;
		word2[4] = 'd';
		cout << word2 << endl;
		word2[5] = '\n';
		cout << word2 << endl;

		inData.close();
    }else cout << "Cannot find this file " << endl;

	

system ("pause"); 
return 0;
}
I believe it's just
char *word2 = word.c_str();
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main() {

	string word;
	ifstream inData("data.txt");
	
	if(inData.is_open())
    {
        getline (inData,word);
		cout << word <<endl;
		char *word2 = word.c_str();
		word2[0] = 'h';
		cout << word2 << endl;
		word2[4] = 'd';
		cout << word2 << endl;
		word2[5] = '\0';
		cout << word2 << endl;

		inData.close();
    }else cout << "Cannot find this file " << endl;

	

system ("pause"); 
return 0;
}


sorry, still doesnt compile
error line 15 can't intitialize char* with a value of type const char*
What are you attempting to accomplish with this source code?
Last edited on
Hi, thanks that seems to work, Its meant to just read a word from a file and then edit a few letters and then display it, I may have not approached it in the best way but this is what I got to after much fiddling. Its just a simple program as an example of how to read and write to files.EDIT: Out of interest id like to know how to choose which lines in particular to read from the file.
Last edited on
[...] Its meant to just read a word from a file and then edit a few letters and then display it [...]

Why do you initialize the character pointer to the pointer returned by the 'c_str()' member function of the std::basic_string class? The code below is unnecessary.
 
char *word2 = const_cast<char*>(word.c_str());

The preceding source code uses the subscript operator to access the contents of the array, which can be done with the object (word) declared earlier in the source code. The std::basic_string class defines two ways that allow you to pass an argument of a numeric data type used as an index to access the contents of the object - std::basic_string::at() and std::basic_string::operator[].

http://en.cppreference.com/w/cpp/string/basic_string/at
http://en.cppreference.com/w/cpp/string/basic_string/operator_at

If you would like to continue using your method, then fine. I just felt the need to mention the information above.


EDIT: Out of interest id like to know how to choose which lines in particular to read from the file.

I don't believe there is a function or member function that allows you to specify the line that you wish to read from a file. You can either choose to use the std::basic_istream::seekg() member function or count the amount of newline characters that appear in the file.
Last edited on
Thanks for the info, Is there anything bad about the way Ive done it? or is it simpler or more efficient to use basic_string?

I only ask about accessing specific lines as the next part of the problem requires you to take words from one text file, combine them and output them to a text file, i guess i could just use extra files to make things simple i.e 1 text file for each word, then one for the output sentance?
char *word2 = const_cast<char*>(word.c_str());

NO!!!!!!!!!!!!!!!

No no no no no!


You absolutely must not cast away the const qualifier for something like c_str(). It's const for a reason. What you're doing is undefined behavior (read: very, very bad).


The real question here is... why do you need a char[] at all? Why can't you just use the string you have?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    string word;
    ifstream inData("data.txt");
    
    if(inData.is_open())
    {
        getline (inData,word);
        cout << word <<endl;
//        char *word2 = const_cast<char*>(word.c_str());  // <- get rid of this crap
        word[0] = 'h';  // <- this works just fine with strings
        cout << word << endl;
        word[4] = 'd';
        cout << word << endl;
        word[5] = '\0';
        cout << word << endl;


The only problem here is that you might be stepping out of bounds of the string. You should check to make sure the length is at least what you expect before you go modifying values:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
        getline (inData,word);
        cout << word <<endl;

        if( word.length() > 0 )
        {     
            word[0] = 'h';
            cout << word << endl;
        }
        if( word.length() > 4 )
        {
            word[4] = 'd';
            cout << word << endl;
        }
        // ... etc 
Last edited on

NO!!!!!!!!!!!!!!!

No no no no no!

You absolutely must not cast away the const qualifier for something like c_str(). It's const for a reason. What you're doing is undefined behavior (read: very, very bad).

Oh, sorry. I've removed the post. I'll refrain from posting code that uses the const_cast operator in a way that could cause undefined behavior. I should have known.

StackOverflow question pertaining to the safety of the const_cast operator: http://stackoverflow.com/questions/357600/is-const-cast-safe?lq=1.

Thanks for the info, Is there anything bad about the way Ive done it? or is it simpler or more efficient to use basic_string?

Yes, I've given you source code that causes undefined behavior. Judging from what I have read and Disch's reaction, it's a very bad thing. I suggest you use one of the two member functions I mentioned in my previous post.

I only ask about accessing specific lines as the next part of the problem requires you to take words from one text file, combine them and output them to a text file, i guess i could just use extra files to make things simple i.e 1 text file for each word, then one for the output sentance?

What is preventing you from storing the words in an array or a container object, combining them to form a sentence, and then writing the sentence(s) to a text file?

I would avoid reading and writing to files when it can be avoided.
Last edited on
This is what i came up with, vivre how would you do it?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
string word2;
	ifstream inData2("data2.txt");
	
	if(inData2.is_open())
    {
        getline (inData,word2);
	}
	inData2.close();

	string word3;
	ifstream inData3("data3.txt");
	
	if(inData3.is_open())
    {
        getline (inData3,word3);
	}
	inData3.close();

	ofstream outData("data4.txt");
	if(outData.is_open())
	{
		outData << word2 << word3 << " of our discontent";
	}else cout << "could not find file";


NB: the out put on data4.txt misses out word2 otherwise the code works fine
Last edited on
Oh, sorry. I've removed the post.


Sorry for my theatrical overreaction. ^^'

But yeah, there are very, very few legitimate uses for const_cast.
This is what i came up with, vivre how would you do it?

I defined a std::vector object containing the file names of every file that contains a word that will be added to the sentence. I then have a for loop traverse the contents of the array. Each cycle of the for loop reads the contents of the file (if the file contains one word) and appends it to the std::string object with the 'sentence' identifier. Once the condition of the for loop evaluates to false, the contents of the std::string object (sentence) and a string literal will be wrote to 'file.txt'.

I believe that is a good solution if the amount of files required to form the sentence could increase or decrease.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <fstream>
#include <string>
#include <vector>

int main(void) {
	const std::vector<std::string> filenames({
		"data.txt", "data2.txt", "data3.txt", "data4.txt"
	});
	std::ifstream readfile;
	std::string sentence;
	for(auto iter = filenames.cbegin(); iter != filenames.cend(); ++iter) {
		readfile.open(*iter);
		if(readfile.is_open()) {
			std::string temp;
			readfile >> temp;
			sentence+=(temp + " ");
		}
		readfile.close();
	}
	std::ofstream savefile("file.txt");
	savefile << sentence << "end the file.";
	savefile.close();
	return 0;
}



Sorry for my theatrical overreaction. ^^'

But yeah, there are very, very few legitimate uses for const_cast.

It's fine. I would have continued to recommend the use of the operator if you hadn't wrote that response informing me of what it causes. Thank you. :)
Last edited on
Topic archived. No new replies allowed.