cooktheprogrammer
cooktheprogrammer

Reputation: 57

Why does getline(cin, string_name) creates an empty string the first time I use it in a loop?

So basically I'll start with the code and my problem is written below.

string words = "";
fstream outFile;
outFile.open(name, fstream::out);
for (int i = 0; i < number; ++i)
{
    getline(cin, words);
    outFile << i << ": " << words << endl;
    words == "";
}

number is given by user.

The thing I wanted to do was to create a file, put as many records as the number says, start each record with its number in order (starting from 0) and then put the text that user writes in console (it is put by getline into the "words" string).

Unfortunately I have a problem because for the record number 0 after colon it breaks a line and in fact it starts copying text from the next record.

Why does it happen? Could someone please explain it?

EDIT:

#include <iostream>
#include <cstdio>
#include <fstream>
#include <string>
using namespace std;


int main()
{       
short int counter_of_commands;
string cmd = "";
string name = "";
cin >> counter_of_commands >> cmd;

if (cmd == "create")
{
    string words = "";
    int records;
    cin >> name;
    cin >> records;
    fstream outFile;

    outFile.open(name, fstream::out);
    for (int i = 0; i < records; ++i)
    {
        if (i == 0)
            getline(cin, words);
        getline(cin, words);
        outFile << i << ": " << words << endl;
        words == "";
    }
    outFile.close();
}

return 0;
}

For input: 1

create example.txt 3

example 111 222

example1 333 444

example 2 444 555

I get:

0: example 111 222

1: example1 333 444

2: example 2 444 555

<- However it creates a fourth row (row #3) just as if after the end of line #2 it clicked enter one more time but didn't write anything. That's not how I would like it to work, it should create an exact number of rows as specified by a user.

Upvotes: 4

Views: 2047

Answers (1)

Danny_ds
Danny_ds

Reputation: 11406

Did you forget a ; here?

for (int i = 0; i < number; ++i)

instead of

for (int i = 0 i < number; ++i)

edit (after comment from OP):

Well, this works fine:

int number = 3;

string words = "";
fstream outFile;
outFile.open("c:/test/test1.txt", fstream::out);
for (int i = 0; i < number; ++i) {
    getline(cin, words);
    outFile << i << ": " << words << endl;
    words == "";
}

But as Vaughn Cato already pointed out, you're probably reading in a previous newline.

Upvotes: 0

Related Questions