Asif Mushtaq
Asif Mushtaq

Reputation: 3798

getline skipping one character for char array

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

Upvotes: 0

Views: 1505

Answers (3)

Scott
Scott

Reputation: 370

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.

Upvotes: 0

Arun A S
Arun A S

Reputation: 7006

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;
}

Upvotes: 2

Ayushi Jha
Ayushi Jha

Reputation: 4023

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];

Upvotes: 0

Related Questions