views:

96

answers:

3

I have a text file made of 3 lines:

Line 1

Line 3

(Line 1, a blank line, and Line 3)

vector<string> text;
vector<string>::iterator it;
ifstream file("test.txt");
string str;

while (getline(file, str))
{
  if (str.length() == 0)
    str = "\n";
  // since getline discards the newline character, replacing blank strings with newline

  text.push_back(str);
} // while

for (it=text.begin(); it < text.end(); it++) 
  cout << (*it);

Prints out:

Line 1
Line 3

I'm not sure why the string with only a newline was not printed out. Any help would be appreciated. Thanks.

+4  A: 

Wasn't? Actually, it was! The reason you have a newline after Line 1 is exactly that empty string with newline in it and nothing else. If not for that second line, you'd see Line 1Line 3 as output. (You said it yourself: getline discards newline characters.)

Apparently, the way I understand your intent, you were supposed to implement your output cycle as follows

for (it = text.begin(); it < text.end(); it++)  
  cout << *it << endl; 

That way you add a newline after each string during output. But if so, then you don't need to manually add a \n character to empty strings during reading.

In other words, decide what is it you want to do. At this time it is not clear.

  • If you want to restore the discarded newline characters during reading, you have to do it for all lines, not just for empty ones.

  • If you want to add the newline characters during output, you don't need to explictly push them into the read lines at all.

In fact, it is a rather strange idea to literally push the newline characters into your strings. What for? Since you already read and store your text line-by-line, the newline characters can be implied. I.e. you can do the printing as I do it above (with endl), and everything will look as expected.

AndreyT
I misunderstood what I wrote then. This code is a side snippet though, I'll try write what I'm trying to do.
kevin
+1  A: 

I'd use something like this:

std::vector<std::string> text;  
std::string str;

while (std::getline(infile, str))
    text.push_back(str);

std::copy(text.begin(), text.end(), 
    std::ostream_iterator<std::string>(std::cout, "\n"));

You're adding complexity that stops your code from working.

Jerry Coffin
+1  A: 

I think the simple answer here, is that getline() strips the trailing newline whether or not there is content in the string. So the three reads you do are as follows:

"Line 1"
""
"Line 3"

which you transform into:

"Line 1"
"\n"
"Line 3"

which when printed is:

Line 1
Line 3
sharth