如何输出小于选框标志大小的选取字符串?

所以我的代码接受一串字母,然后以符号方式输出该字符串,符号大小为5.例如,如果我想输出“Hello World!”,则输出为:

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

但问题是,如果有一串字母长度为8且字幕标志的大小为10,那么我只想在字幕标志中显示一次字符串。 因此,如果字符串的大小小于指示的选框标记,则只显示一次字符串。 例如:

 Input: Activist (the string that I want to output in a sign) 10 (the length of the sign) Output: [Activist ] 

注意在选框标记中仍然有10个空格,它所做的只是简单地输出一次字符串。

这是我的代码。 如果有指示,我已经让它运行了不止一次:

 #include  #include  void ignoreRestOfLine(FILE *fp) { int c; while ((c = fgetc(fp)) != EOF && c != '\n'); } int main(void) { int num_times, count = 0; int marq_length, sign = 0; 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", &marq_length) != 1) { // Deal with error. } ignoreRestOfLine(stdin); size_t n = strlen(s) - 1; int i, j; if (s[strlen(s) - 1] == '\n') s[strlen(s) - 1] = '\0'; printf("Sign #%d:\n", ++sign); for (i = 0; i < n + 1; i++) { putchar('['); for (j = 0; j < marq_length; j++) { char c = s[(i + j) % (n + 1)]; if (!c) c = ' '; putchar(c); } printf( "]\n" ); } } } 

输入和输出如下:

 Input: 3 Hello World! 5 Sign #1: (This is the output) [Hello] [ello ] [llo W] [lo Wo] [o Wor] [ Worl] [World] [orld!] [rld! ] [ld! H] [d! He] [! Hel] [ Hell] Activist 10 Sign #2: (This is the output) [Activist A] [ctivist Ac] [tivist Act] [ivist Acti] [vist Activ] [ist Activi] [st Activis] [t Activist] [ Activist ] LOL 2 Sign #3: (This is the output) [LO] [OL] [L ] [ L] 

一切都是正确的,除了标志#2。 如果字符串的长度小于字幕标志大小,如何在字幕标志中输出一次字符串?

将循环更改为:

  if (n <= marq_length) { printf("[%-*s]\n", marq_length, s); } else { for (i = 0; i < n + 1; i++) { putchar('['); for (j = 0; j < marq_length; j++) { char c = s[(i + j) % (n + 1)]; if (!c) c = ' '; putchar(c); } printf("]\n"); } }