1

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

So does that even means that getchar() will read the next character every times that i used no matter where? It this the only way to write it?
@Grasshelicopter Yes, getchar will read the next character if you will not even assign its result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.