0

I'm currently studying basic c++, and I've encountered a problem that I can't deal with. In the below code you can see my program. What's bad about it, is that from the cout << word; I can see the content of my text file, but the cout << astring doesn't show me anything. Could anyone please point me out the mistake?
P.s. It has to be done with functions.

void read(string word); int main() { string astring; read(astring); cout << astring; return 0; } void read(string word) { ifstream duom ("info.txt"); if (duom.is_open()) { while(!duom.eof()) { getline(duom, word); cout << word; } } else cout << "File couldn't be opened"; } 

4 Answers 4

2

Your function read takes a copy to the string and reads into this temporary. To read into the input parameter, use reference like so:

void read(string& word); 
Sign up to request clarification or add additional context in comments.

Comments

1

The problem is that the read function doesn't change astring in main, astring is passed to the read function it is not returned from the read function. You should change read, either like this

void read(string& word); // pass a reference to a string to read int main() { string astring; read(atring); 

or like this

string read(); // return a string from read int main() { string astring = read(); 

The second version is generally preferred.

Comments

1

Try passing a reference to the function: void read(string& word); so that you can later use the actual word, not its local copy.

Comments

0

you should use reference or pointer like

void read(string& word); or void read(string *word); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.