Can anyone explain why not in all cases cin.getline

today on hackerrank i did a problem known as designer pdf but it was not accepting cin.getline()
i dont know why
hackerrank problem link


my code using cin.getline:(this didnt get accepted)

my code using cin but not cin.getline

@yaswanth0412 when you used cin>> to take array input it leaves ā€œ\nā€ (when pressed enter after taking array input) in the input buffer which is encountered by cin.getline() and cin.getline terminates after reading upto that ā€œ\nā€ and hence will not read your string. use cin.get() or cin.ignore() before cin.getline() to take that ā€œ\nā€ out of input buffer.
and take your ch size >10.

yes thank you for the best explanation but why should i take size>10

when given word is of size 10 your variable a inside while loop can go upto a=10 and ch[10] is not valid so may give run error.

thank you for solving my question

1 Like