Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with character array input and output in C

Tags:

c

I wrote the following code to read a character array and print it.

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void read_array(char a[],int n);
void print_array(char a[],int n);
int main(void)
{
    char a[100];
    int n;
    printf("\nEnter n:");
    scanf("%d",&n);
    printf("\nEnter the characters:");
    read_array(a,n);
    printf("\nThe array now is: ");
    print_array(a,n);
    getch();
    return 0;
}

void read_array(char a[],int n)
{
     int i;
     for(i=0;i<n;i++)
         scanf("%c",&a[i]);

}
void print_array(char a[],int n)
{
     int i;
     for(i=0;i<n;i++)                
        printf("a[%d]=%c\n",i,a[i]);
}

Input:

Enter n:15  
Enter the characters:xxxxx     xxxxx  

Output:

The array now is:  
a[0]=    
a[1]=x    
a[2]=x    
a[3]=x    
a[4]=x    
a[5]=x    
a[6]=    
a[7]=    
a[8]=    
a[10]=    
a[11]=x    
a[12]=x   
a[13]=x    
a[14]=x    

Where in my input a[5] through a[9] are blank characters. So how come in the output a[0]=(a blank)?

like image 778
station Avatar asked Dec 02 '25 16:12

station


1 Answers

The first character you're reading in is the newline you typed to enter the 15. Use fgets() and sscanf() - you'll be much happier.

like image 91
Carl Norum Avatar answered Dec 04 '25 06:12

Carl Norum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!