What operators do I use to transport a bundle of code onto a .txt file (if that is even possible)? |
fstream is just like any other stream. You use it the same way you use cout and cin statements.
Lets say you want to write 10 lines that say "Hello!" to the console. How would you do that? Most likely you would do something like this.
1 2
|
for (int i = 0; i != 10; ++i)
std::cout << "Hello!" << std::endl;
|
Easy right?
Now how would we do the same thing but instead write 10 lines of "Hello!" to a text file? Well it is basically the same exact thing.
1 2 3 4
|
std::ofstream output("test.txt"); // Open the text file
for (int i = 0; i != 10; ++i)
output << "Hello!" << std::endl; // We use output just like it was a cout statement
|
Pretty simple :). We basically use a ofstream like we would use cout but instead of displaying to the console as we do with std::cout we are putting the information into whatever file we opened with our ofstream object.
Now there is some other things you should know about fstream and I would recommend you head on over to the tutorial on this site that talks about it. It should give you a good grasp of using ofstream and ifstream http://www.cplusplus.com/doc/tutorial/files/
What operator is used to display the .txt file after I have done that? |
Now when you say display do you mean open that said .txt file in like notepad? Or display it's contents in the console? I am thinking your professor means the latter.
To display things from a file on the console you would use the ifstream objects. They work just like ofstream does but instead of writing stuff to a file they read stuff from a file.
For example.
1 2 3 4 5
|
std::ifstream fromFile("testing.txt"); // Stream which will read from a file
std::string word; // Variable that will hold each word from the file.
while (fromFile >> word)
std::cout << word << std::endl; // Display every word from the file.
|
Again I would check out the tutorial on this site to a more in depth answer on how to do this and how it works.
fstream some_file.open("text.txt"); //Does the file text.txt need to already have been opened? If not will this open it?
No that file text.txt doesn't already need to be opened. And yes that code will open that file but not in the way I believe you are thinking. It won't open the file in notepad or anything like that so that you can see it. What it is doing is giving your program access to what that file contains and also giving it access to write things to that file.