0

why cin.getline is skipping one character?

Here is code:

#include <iostream>
using namespace std;
int main(){
    char b[5];
    cin.ignore();
    cin.getline(b,5);
    cout << b;
   return 0;
}

if I removed cin.ignore(); then it will skip the last character.. Example If i input abcde it will show now bcde When I removed cin.ignore(); it will show abcd

Asif Mushtaq
  • 3,658
  • 4
  • 44
  • 80
  • possible duplicate of [Program skips cin.getline()](http://stackoverflow.com/questions/11835226/program-skips-cin-getline) – Ayushi Jha May 02 '15 at 18:47

3 Answers3

2

You need an extra space to store a Null character. Change your string to

char b[6];

C strings are terminated with a Null character ( '\0' ), so if you need a string that can store 5 characters, you need to create one which can store 6 characters ( the extra space for a Null character )

So you can remove the cin.ignore() now as it reads the first character you enter and then discards it.

Try

#include <iostream>
using namespace std;
int main(){
    char b[6];
    cin.getline(b,6);
    cout << b;
   return 0;
}
Arun A S
  • 6,421
  • 4
  • 29
  • 43
  • I know that, but why this causing the issue? Even I tried your method and input like abcde why it's skipping the first a? please try yourself and input abcde on your code. – Asif Mushtaq May 02 '15 at 18:34
  • @AsifMushtaq , I forgot to remove the `cin.ignore()`. Remove it and try it. – Arun A S May 02 '15 at 18:34
  • you mean I need always one additional size number to my required size? But sorry to bother you, can you explain why it's happening? – Asif Mushtaq May 02 '15 at 18:39
  • @AsifMushtaq , Yes. [why a char array must end with a null character](http://stackoverflow.com/questions/10261672/why-a-char-array-must-end-with-a-null-character) – Arun A S May 02 '15 at 18:40
0

Always take into account the NULL character (\0). Make sure there is atleast one extra space for it. If your input string is n chars long, your char array should be declared as b[n+1], to accommodate the Null character. Null character is important because it acts a string terminating character, any proper string must be null-terminated.
So, for instance, you want to input a 5-char long string, declare the char array as 6 elements long: char b[6];

Ayushi Jha
  • 4,003
  • 3
  • 26
  • 43
0

Since you're using C++, you would be better off using std::string to avoid these little nuances. It is important to know how C strings work though.

Scott
  • 370
  • 2
  • 7