关于#c语言#的问题:我不理解为啥输出完100个字母之后会输出汉字

我不理解为啥输出完100个字母之后,会继续输出几个汉字哇?有没有解决方法各位亲,谢谢各位了orz

void practice() {
    char putout[100]{};
    srand(time(NULL));
    int i, j;
    for (i = 0; i < 100; i++) {
        putout[i] = rand() % 25+1 + 'a';
    }
    printf("%s", putout);
}

int main() {
    while(1) {
        printf("是否开始打字训练?1(继续)/2(取消)\n");
        int n;
        char input[100];
        scanf_s("%d", &n);
        if (n == 1) {
            practice();
            scanf("%s", &input);
        }
    }
}

img

字符串末尾没 '\0'
还有一些其他的小毛病
稍微帮你修改了一下

void practice() {
    char putout[101];
    int i, j;
    for (i = 0; i < 100; i++) {
        putout[i] = rand() % 25 + 1 + 'a';
    }
    putout[100] = '\0';
    printf("%s\n", putout);
}
int main() {
    srand(time(NULL));
    while (1) {
        printf("是否开始打字训练?1(继续)/2(取消)\n");
        int n;
        char input[101];
        scanf_s("%d", &n);
        getchar();
        if (n == 1) {
            practice();
            scanf("%s", &input);
        }
    }
}

在输出字符数组 putout 时,输出的是字符数组中的所有字符,包括字符串结尾的空字符 '\0'。

在初始化字符数组 putout 时,你可以将所有的字符初始化为空字符'\0',这样在输出字符数组时,就只会输出随机生成的字符,而不会输出汉字。修改后代码如下

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void practice() {
  char putout[100] {
  }
  ;
  srand(time(NULL));
  int i;
  for (i = 0; i < 100; i++) {
    putout[i] = rand() % 25+1 + 'a';
  }
  printf("%s", putout);
}
int main() {
  while(1) {
    printf("是否开始打字训练?1(继续)/2(取消)\n");
    int n;
    char input[100];
    scanf("%d", &n);
    if (n == 1) {
      practice();
      scanf("%s", input);
    } else if (n == 2) {
      break;
    }
  }
  return 0;
}