This week I started studing a text files in C++ and in my exercice I have to do a program that the user enter the lines in the file, but… for each space that the user enters, the program asking the new to user.
Here is my code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(void){
ofstream myfile;
string answer;
do{
cout << "Insert a line in the file[END to finalize]: ";
cin >> answer;
myfile.open("example.txt");
myfile << answer;
myfile.close();
}while(answer != "END");
}
The result is:
Insert a line in the file[END to finalize]: Hello my friend
Insert a line in the file[END to finalize]: Insert a line in the
file[END to finalize]: Insert a line in the file[END to finalize]:
operator>>(istream&, string&)basically grabs the next word. If you want to grab a whole line, trystd::getline(std::cin, answer);.getlinewon’t include the newline, though. Meaning you’ll have to do something likemyfile << answer << '\n';to output them as lines.BTW, in most cases you’d want to either open the file outside the loop, or open it for appending with something like
myfile.open("example.txt", ios::app);. Opening the file in the loop each time like you’re doing, i’m pretty sure you position the file pointer at the beginning of the file, so each line you write will overwrite at least the first part of the previous line.