Home > database >  user input of name using getchar() then diplaying the name. (c code)
user input of name using getchar() then diplaying the name. (c code)

Time:12-15

What I was prompted to code:

Prompt the user to enter his/her name using getchar() function then print the entered name on the screen.

What I coded:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int c;                
    int i;
    char arr[20]={0};
    c = getchar();
    i = 0;
    for(i;i<20;i  )
    {
        arr[i]=c;
        c=getchar();
    }
   
    for (int j=0;j<20;j  )
    {
        printf("%s",arr[j]);
    }
}

My result is not working right at all, and there are all types of issues. For example, I do not know how to stop the loop if the user already entered the full name. Instead, I have to keep pressing Enter until EOF. Another issue is the name is not printing on the screen again. I believe the basis of my thinking is false with this code. Can anyone point me in the right direction?

CodePudding user response:

try this:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i;
    char arr[21], c;
    for(i = 0; (c = getchar()) != '\n' && c != EOF && i < 20; i  )
    {
        arr[i] = c;
    }
    arr[i] = '\0';

    printf("\n%s", arr);
}

run, type your phrase and press enter

  • Related