-3

enter image description here

the image shows the input taken and output shown .

I am taking character array as input and printing it, now when i print it, it print input characters as well as some additional random characters, why so??

#include<iostream>
int main()
{
    int n;
    std::cin>>n;

    char array[100]; 
    
    for(int i=0; i<n; i++) 
    {
        std::cin>>array[i];
    }
    
    std::cout<<array;

    return 0;
}

I was expecting it to be printing the letters that i provides as input but it is printing additional character as well as.

2 Answers2

4

An array of char is treated as string and strings are \0 terminated. Your mixing of int and char is somewhat odd, but assuming it is what you want, you just need to add the terminator:

#include<iostream>
int main()
{
    int n;
    std::cin>>n;

    char array[100]; 
    
    for(int i=0; i<n; i++) 
    {
        std::cin>>array[i];
    }
    array[n] = '\0';
    
    std::cout<<array;

    return 0;
}

Though you should use std::string for strings. The above code will invoke undefined behavior when the user enters 100 or more for n.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
3

The line

std::cout<<array;

requires that array is a valid C-style string, which is an array of characters terminated by a null character. You are violating this rule, by not ensuring that the string is null-terminated.

Your program is printing garbage characters because that line of code will continue printing characters until it happens to find a null character (i.e. a character with the character code 0).

I suggest that you add the line

array[n] = '\0';

to add a terminating null character after the loop.

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39