0
#include <iostream>
#include <string>
#include <set>
using namespace std;    
int main()
{
   int N; //number of bank accounts
   cin >> N;
   int n = 0;
   multiset<string> bank_accounts;
   string account;
   while (n < N)
   {
     getline(cin, account);
     bank_accounts.insert(account);
     n++;
   }        
}

When I input N = 1 , the loop doesn't take any input and the program exits but when instead of getline(cin, account) I use cin >> account it works . I have inputs which have spaces so I need to use getline() only but I can't understand this strange behaviour .

Suji
  • 1,298
  • 1
  • 12
  • 27
abkds
  • 1,667
  • 5
  • 26
  • 40
  • I can't believe "N == 1" is the problem. I'm guessing you'll see the *same* problem with *any* value of "N". SUGGESTION: step through the code under your debugger. Q: What platform/compiler/IDE are you using? Which debugger is most convenient for you to try? – FoggyDay Aug 12 '14 at 05:25

1 Answers1

3

Your cin >> N left a new line character (that you typed) in the buffer, which you immediately consumed when your first called getline().

You can ignore this character by doing cin.ignore(); before your first getline.

quantdev
  • 22,595
  • 5
  • 47
  • 84
  • +1 Sometimes there are many misleading with `cin` and `getline` when using them together and catching the problem is not too easy. Good catch. – masoud Aug 12 '14 at 05:33