station
station

Reputation: 7145

Problem with character array input and output in 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)?

Upvotes: 3

Views: 3913

Answers (3)

Piyush Agarwal
Piyush Agarwal

Reputation: 102

While taking input in case of char array using scanf, it also captures the enter key that you presses while entering the input on a new line, so this problem is happening.

You may use getchar if you want each character to be present as input.

Upvotes: 0

Pruthvid
Pruthvid

Reputation: 683

In the scanf function for getting the values of character use getche or getchar function. This will allow you to capture all the characters including new line. you can skip the first character and copy the rest.

Upvotes: 1

Carl Norum
Carl Norum

Reputation: 225202

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.

Upvotes: 2

Related Questions