0

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

  1. The user inputs the name of the file they want to create.

then

  1. In the same line they input an integer amount=the number of lines of the text of the newly created txt file.

  2. In a new line the user input the first line of the text, in a new line the next line and so on.

  3. 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?

dragosht
  • 3,177
  • 2
  • 20
  • 30
Bilbo
  • 125
  • 5
  • I'm voting to close this question as off-topic because it pertains to a simple and unusual coding mistake, and is unlikely to help future readers. – Beta Dec 21 '15 at 14:45
  • Two notes: 1) stream input (`cin >> ...`) and `getline` don't play well together, so you must make allowances, and 2) it is best to develop new functionality *in isolation* as much as possible-- you should get **user input** and **file output** working perfectly before you try to combine them. – Beta Dec 21 '15 at 14:49

2 Answers2

3

You have two ostreams, start and out. You attach out to the file (and write nothing to it), and write to start (which is attached to nothing).

Beta
  • 86,746
  • 10
  • 132
  • 141
1

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;
}
Thirupathi Thangavel
  • 2,124
  • 2
  • 22
  • 44