1

PROBLEM: I have to print a string (character per character) several times in a same line but as soon as upper loop executed once line changes. So how to print it in a same line?

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

int main()
{
    char name[100];
    int m;
    printf("Enter the string\n");
    fgets(name, 100, stdin);                                        
    printf("Number of times you have to repeat the string\n");
    scanf("%d", &m);                                                
    int n = strlen(name);
    for (int j = 0; j < m; j++)
    {
        for (int i = 0; i < n; i++)
            printf("%c ", name[i]);
    }
    return 0;
}

INPUT:

 Enter the string
  I LOVE TO EAT
Number of times you have to repeat the string.
 3

MY OUTPUT:

I L O V E T O E A T 
 I L O V E T O E A T 
 I L O V E T O E A T 
 

EXPECTED OUTPUT:

I L O V E T O E A T I L O V E T O E A T I L O V E T O E A T 
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Andrew
  • 49
  • 4

1 Answers1

2

Just add one more statement after the call of fgets.

fgets(name, 100, stdin);
name[ strcspn( name, "\n" ) ] = '\0';

That is fgets can append the input string with the new line character '\n' that you should remove.

Pay attention to that calling the function strlen the value of which is used in the inner loop is inefficient.

You could write instead.

for (int j = 0; j < m; j++)
{
    for ( const char *p = name; *p != '\0'; ++p )
        printf("%c ", *p);
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335