开发者

Problem with character array input and output in C

开发者 https://www.devze.com 2023-02-22 12:00 出处:网络
I wrote the following code to read a character array and print it. #include<stdio.h> #include<stdlib.h>

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]);

}
开发者_JAVA百科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)?


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.


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.


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.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号