Search code examples
carraysfor-loopcharactergetchar

Input and output a set of character with an array by using getchar() and putchar()


I am newbie to the world of C programming language and not so familiar with the function putchar() and getchar().I try to write a code that read a set of character inputted and store it in an array. Here is my code:

#include<stdio.h>
#include<ctype.h>
#define MAX_SIZE 100

int main(){
    int i;
    char c[MAX_SIZE]={0};
    printf("Enter message:");

    for(i=0;getchar()!='\n';i++){
        c[i] = getchar();    /*looks like some error here that the compiler didn't found out.....*/
    }

    for(i=0;c[i]!='\n';i++){
        putchar(c[i]);
    }

    return 0;
}

The program runs successfully but didn't work well. The result outputted is chaotic and totally have no meaning. I wonder what's wrong with my code as it looks no error for me(so does the compiler seen correct to it). I wish i can get an explanation besides getting a correct way to write it.


Solution

  • Instead use the following

    int value;
    
    for ( i = 0; i < MAX_SIZE && ( value = getchar() ) != EOF && value != '\n'; i++ )
    {
        c[i] = value;
    }
    
    for ( int j = 0; j < i; j++ )
    {
        putchar( c[j] );
    }
    
    putchar( '\n' );
    

    Otherwise at least in this loop

    for(i=0;getchar()!='\n';i++){
            ^^^^^^^^   
    

    you are skipping each even character

    And the header <ctype.h> may be removed because neither declaration from the header is used in the program.