Please can someone show me how would I create a file using fstream
that would take the contents from another existing file and user input sentence.
for example:
I have file1 with some contents
The user inputs a sentence
Now I want to create a file using streams that has contents of file1 and sentence.

My possible coding

ofstream output;
output.open("file2.txt");
output<<file1 + sentence<<endl;
output.close();

To me something in the code does not seem right.

Recommended Answers

All 4 Replies

How to do it depends on the contents of file1. If file1 only contains one line of text then it should be pretty simple

ifstream file1("filename.txt");
ofstream file2("outfile.txt");
string input = "Hello World";
string line;
file1 >> line;
file2 << line << input;

It becomes a little more complex when the contents of file1 is more than one line. In that case you need to use a loop to read file1 and write to file2.

Just in case you forgot. You can easily append to the end of the file.
Use

std::string input="Hello at the end";
std::ofstream File("file1.txt",std::ios::app);
File<<input<<<std::endl;        // This is written at the end of the file.

Obviously, if you don't want to change the original, you need to make a copy, but often a simple system command will do that for you, without having to worry about writing a loop/reading/writing etc.

Thanks, I knew I was forgetting some simple command but was not sure about it.

If that solves your problem, please mark the thread as solved.
(You can always start a new one with a different problem).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.