1

I am trying to store individual character(including the spaces) of a sentence in a char array like "Do or die" but whenever I print the array (char arr) it does not print the last character in the array i.e. 'e'.

Can somebody tell why is this happening . I am a beginner in c++.

#include<iostream>
using namespace std;

int main()
{
    int n;

    cout << "Enter the length of the array\n";
    cin >> n;

    char arr[n + 1];

    cin.ignore(n, '\n');

    cout << "Enter the characters of the array\n";
    cin.getline(arr, n);

    for(int i = 0; i < n; i++)
        cout << arr[i] << endl;

    return 0;
}
mch
  • 9,424
  • 2
  • 28
  • 42
  • 2
    [C++ doesn't have variable-length arrays](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard). For strings use `std::string`. Otherwise for "arrays" with a size known only at run-time use `std::vector`. – Some programmer dude Oct 01 '21 at 10:44
  • With that said, think about the loop condition `i – Some programmer dude Oct 01 '21 at 10:45

2 Answers2

1
  1. Here you need to understand how cin.getline(arr,n) works.
  2. it will extract characters from the stream and stores them into arr until n characters have been written into arr (including the terminator null character).

So if you change this cin.getline(arr, n) to cin.getline(arr, n+1) this, it will work perfectly.

Jitu DeRaps
  • 144
  • 1
  • 9
1

First in C++, the size of an array must be a compile-time constant.So, take for example the following code snippets:

int n = 10;
int arr[n]; //INCORRECT because n is not a constant expression

The correct way to write the above would be:

const int n = 10;
int arr[n]; //CORRECT

Similarly, the following(which you did in your code example) is incorrect:

    int n;
    cout << "Enter the length of the array\n";
    cin >> n;
    char arr[n + 1]; //INCORRECT

Second the reason you're not getting the last character printed on screen is because the size of you array is n+1 but in your for loop:

for(int i = 0; i < n; i++)

you're only going upto n. You should replace the above with:

for(int i = 0; i < n + 1; i++)// note that +1 ADDED HERE

A better solution would be to use std::string for your purpose as shown below:

#include<iostream>


int main()
{
    std::string inputString;

    std::cout << "Enter the string"<<std::endl;
    std::getline(std::cin, inputString);
    
    //first way to print the string 
    std::cout << inputString << std::endl;

   //second way to print the string 
   for(int i = 0; i < inputString.size(); ++i)
   {
       std::cout << inputString[i];
   }
    
    return 0;
}
Jason
  • 36,170
  • 5
  • 26
  • 60