Home > Mobile >  How to remove extra "\n" in output in c
How to remove extra "\n" in output in c

Time:10-01

while the output of the code is the correct one, an extra line is being printed before the answer. How to remove the extra "\n" being printed before the output of the executed code?

#include <stdio.h>
#include <string.h>

int     main(void)
{
    int     nbr_words;
    char    word_1[51];
    char    word_2[51];
    int     i;

    scanf("%d\n", &nbr_words);

    char    temp_word_1[nbr_words][51];
    char    temp_word_2[nbr_words][51];

    i = 0;
    while (i < nbr_words)
    {
        scanf("%s ", word_1);
        strcpy(temp_word_1[i], word_1);
        scanf("%s", word_2);
        strcpy(temp_word_2[i], word_2);
        i  ;
    }

    while (nbr_words >= 0)
    {
        printf("%s %s\n", temp_word_2[nbr_words], temp_word_1[nbr_words]);
        nbr_words--;
    }
    return (0);
}

output:

2
travail work
verite truth

truth verite
work travail

CodePudding user response:

Your first print is out of bounds: temp_word_1[nbr_words] does not exist. Valid elements are temp_word_1[0] to temp_word_1[nbr_words - 1] (same, of course, for temp_word_2).

        while (nbr_words >= 0)
        {
            printf("%s %s\n", temp_word_2[nbr_words], temp_word_1[nbr_words]);
            nbr_words--;
        }

        while (nbr_words--)
        {
            printf("%s %s\n", temp_word_2[nbr_words], temp_word_1[nbr_words]);
        }
  •  Tags:  
  • c
  • Related