Search code examples
cprintfgetchar

String input with getchar


I've a little problem with my code, why when I use printf on string1 (last line), it doesn't give me what I wrote for this variable ?

For example if I wrote : asdfgh, string1 give me something weird like : @>>..

Any idea ?

Thanks for help.

 int main()
{
    int length;
    int i = 0;
    char string1[100];
    printf("Please enter the length of the two strings\n");
    scanf("%d", &length);

    printf("\nPlease enter the first string\n");
    while((string1[i] = getchar())!='\n')
        i++ ;
    getchar();
    printf("\nString 1 : %c", string1);

    return 0;
}

Solution

  • You have few problems there:

    1) Should use %s for printing string.
    2) Terminate the string with NULL terminator (It's not a string until then ;)
    3) use a standard prototype for main(), such as: int main(void)