-1

Here is my code:

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

void ignoreRestOfLine(FILE* fp)
{
   int c;
   while ( (c = fgetc(fp)) != EOF && c != '\n');
}


int main( void )
{
    int num_times, count =0;
    int length;
    scanf("%d ", &num_times);
    char s[100];
  for(count=0 ;count<num_times;count++){

    if ( fgets(s, sizeof(s), stdin) == NULL )
    {
       // Deal with error.
    }

    if ( scanf("%d", &length) != 1 )
    {
       // Deal with error.
    }

    ignoreRestOfLine(stdin);

    size_t n = strlen( s );
    size_t m = 5;
    int i,j;
    for (  i = 0; i < strlen(s)+1; i++ ){
        putchar( '[' );
        for (  j = 0; j < m; j++ )
        {
            char c = s[(i + j) % ( n + 1 )];
            if ( !c )
                c = ' ';
            putchar( c );
        }
        printf( "]\n" );
    }


    }
}

The first line is to indicate the number of signs I want to input. The second line is where i type in the string that i want my sign to output. And the third line is the number of spaces inside the marquee. For example:

Input:
1
Hello World!
5

Output:
[Hello]
[ello ]
[llo W]
[lo Wo]
[o Wor]
[ Worl]
[World]
[orld!]
[rld! ]
[ld!  ]
[d!  H]
[!  He]
[Hel ]
[ Hell]

But this what my code actually does:

Input: 
1
Hello World!
5

Output:
[Hello]
[ello ]
[llo W]
[lo Wo]
[o Wor]
[ Worl]
[World]
[orld!]
[rld!
]
[ld!
 ]
[d!
 H]
[!
 He]
[
 Hel]
[ Hell]

How can i fix this simple error?

2 Answers2

1

It's because you're reading the newline from stdin . you ignore the newline on your number of times input, but not on the string input. You need to chop off the newline character from s. removing-trailing-newline-character-from-fgets-input

Community
  • 1
  • 1
Jimi WIlls
  • 348
  • 1
  • 10
1

This is because the fgets function reads in an entire line up to either end-of-file or a linefeed (\n) character. If it gets to a \n, it will append it to the end of the string before returning it. If you do not want that linefeed in your string (which you do not in this case), you will want to strip it off using something like this:

if (s[strlen(s)-1] == '\n')
  s[strlen(s)-1] = '\0';

This will replace the linefeed character with a NULL byte, shortening the string by exactly one character and should make your code work the way you intend.

Joel C
  • 2,958
  • 2
  • 15
  • 18