Pergunta

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;
}
Foi útil?

Solução

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)

Outras dicas

 #include <stdio.h>
 int main(void)
 {
    int length;
    int i = 0;
    int ch;
    char string1[100];
    printf("Please enter the length of the two strings\n");
    scanf("%d", &length);
    getchar();
    printf("\nPlease enter the first string\n");
    /* use null for termination of string */
    /* Press Ctrl+d to end your input */
    while((ch = getchar()) != EOF){
            string1[i++] = ch;

    }
    string1[i] = '\0';
    /* USE %s to print whole string */
    printf("\nString 1 : %s\n", string1);

    return 0;
  }

Hope this will solve your problem

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top