Odd behavior of getline function

I successfully submitted the problem : http://www.codechef.com/problems/DIRECTI

again a good problem for STL learner in C++.

But I saw a strange behavior of getline function. It did not use my string container efficiently – by leaving the 0 subscript space of string container as empty.

My solution is : http://www.codechef.com/viewsolution/1727919

Why is it so? Please suggest.

also getline function is not working properly in test cases like structure …:frowning:
kindly suggest me a method to input a string that may or may not have the spaces in them …???

If I have understood the problem correctly, then it is not odd behavior but expected behavior.

Your code snippet-

cin>>n;               // 1
string a[n+5];        // 2
for(int i=0;i<=n;i++) // 3
getline(cin,a[i]);    // 4

has following problems

  1. On line 1 you have read from cin. Here cin reads the integer, but leaves the end-of-line character(\n). The behavior of getline() is to read upto the delimiter (default is ‘\n’) and discard delimiter. So immediately after cin, the first call to getline() is bound to return an empty string. So that’s why you need to call getline one extra time (or in your words “leaving the 0 subscript space of string container as empty”).
  2. This is just advice - instead of array of string, use vector of string.
  3. Another advice - It is hard to tell that line 4 is in loop, indent it properly.