Home > Software design >  last character of my character array is getting excluded
last character of my character array is getting excluded

Time:06-20

int n;
cin>>n;
cin.ignore();

char arr[n 1];
cin.getline(arr,n);
cin.ignore();
cout<<arr;

Input: 11 of the year

Output: of the yea

I'm already providing n 1 for the null character. Then why is my last character excluded?

CodePudding user response:

You allocated n 1 characters for your array, but then you told getline that there were only n characters available. It should be like this:

int n;
cin>>n;
cin.ignore();

char arr[n 1];
cin.getline(arr,n 1);  // change here
cin.ignore();
cout<<arr;

CodePudding user response:

Per cppreference.com:

https://en.cppreference.com/w/cpp/io/basic_istream/getline

Behaves as UnformattedInputFunction. After constructing and checking the sentry object, extracts characters from *this and stores them in successive locations of the array whose first element is pointed to by s, until any of the following occurs (tested in the order shown):

  1. end of file condition occurs in the input sequence (in which case setstate(eofbit) is executed)
  2. the next available character c is the delimiter, as determined by Traits::eq(c, delim). The delimiter is extracted (unlike basic_istream::get()) and counted towards gcount(), but is not stored.
  3. count-1 characters have been extracted (in which case setstate(failbit) is executed).

If the function extracts no characters (e.g. if count < 1), setstate(failbit)is executed.

In any case, if count > 0, it then stores a null character CharT() into the next successive location of the array and updates gcount().

In your case, n=11. You are allocating n 1 (12) chars, but telling getline() that only n (11) chars are available, so it reads only n-1 (10) chars into the array and then terminates the array with '\0' in the 11th char. That is why you are missing the last character.

of the year
         ^
        10th char, stops here

You need to 1 when calling getline(), to match your actual array size:

cin.getline(arr,n 1);
  • Related