I've read the answers to the "The Questions that may already have your answer" but it didn't help me.
I suppose my problem has a quick solution.
I want to write a program in which
then
In the same line they input an integer amount=the number of lines of the text of the newly created txt file.
In a new line the user input the first line of the text, in a new line the next line and so on.
And all those lines are saved to the created file.
For example file.txt 3
bhjudshsu 565 jdd
hcxjs
jdckisa jsdjs
And after opening the file named file.txt I should see the above three lines of the text.
Here is my code sample:
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
int amount;
string fileName, line;
ofstream start;
cin>>fileName>>amount;
ofstream out(fileName.c_str());
for(int i=0; i<amount; i++)
{
getline(cin, line);
start<<line<<endl;
}
start.flush();
start.close();
return 0;
}
The problem is that the file is created but it is empty.
Moreover, if I input file.txt 3
the program is closed after I input only two lines.
Could you tell me what I am doing wrong?
In addition to Beta's answer, cin>> will leave newlines in the buffer when the user presses enter. getline() reads this as the user having pressed enter to "skip" the input.
You can use cin.ignore() to get rid of those extra characters before using getline().
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
int amount;
string fileName, line;
cin >> fileName >> amount;
ofstream start(fileName.c_str());
for(int i = 0; i < amount; i++)
{
cin.ignore();
getline(cin, line);
start << line << endl;
}
start.flush();
start.close();
return 0;
}