#Why is my word printing out one too many times?

29 messages · Page 1 of 1 (latest)

gray shellBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

keen prairie
#
#include <stdio.h>

#define MAX 1024

int main(void) {
    char word[MAX];

    printf("Input word: ");

    fgets(word, MAX, stdin);

    int length_of_word = 0;
    for (int i = 0; word[i] != '\0'; i++) {
        printf("%c", word[i]);
        length_of_word++;
        printf("%d", length_of_word);
    }
    
    printf("Word square is\n");
    for (int i = 0; i < length_of_word; i++) {
        printf("%s", word);
    }

    return 0;
}```
#

upon doing some in-code testing

#

it prints out

#
b1r2u3h4
5Word square is
bruh
bruh
bruh
bruh
bruh```
#

so its including the newline character in the loop

#

?????

#

do i not understand how for loops work or something lmao

#

what

#

i tried this witha while loop

#

same thing

#

i am relaly confused rn

tired gull
#

;compile | bruh

#include <stdio.h>

#define MAX 1024

int main(void) {
    char word[MAX];

    printf("Input word: ");

    fgets(word, MAX, stdin);

    int length_of_word = 0;
    for (int i = 0; word[i] != '\0'; i++) {
        printf("%c", word[i]);
        length_of_word++;
        printf("%d", length_of_word);
    }
    
    printf("Word square is\n");
    for (int i = 0; i < length_of_word; i++) {
        printf("%s", word);
    }

    return 0;
}
frail fjordBOT
#
Program Output
Input word: b1r2u3h4Word square is
bruhbruhbruhbruh
tired gull
#

Prints only 4 times.
Not sure why yours prints 5 times.

wheat ledge
wheat ledge
#

fgets places a new line into word, so the for loop will count jt

tired gull
keen prairie
stone spire
#

every standard library function has a man page with complete description of behaviour

#

sorry wrong link

#

(There are POSIX man pages and also Linux man pages, it's confusing at times)

keen prairie
#

thx 🙂

#

.solved

#

!solved

gray shellBOT
#

Thank you and let us know if you have any more questions!

This thread is now set to auto-hide after an hour of inactivity