此代码会产生以下奇怪的输出。我尝试将字符数组增加到 13,它打印了整个字符串,但最后仍然有奇怪的字符。我在 Windows 上使用 MinGW。这可能是原因吗?
#include <stdio.h>
#include <string.h>
int main() {
char message[10];
int count, i;
strcpy(message, "Hello, world!");
printf("Repeat how many times? ");
scanf("%d", &count);
for(i=0; i < count; i++)
printf("%3d - %s\n", i, message);
if(i==count)
getch();
}
最佳答案
这是因为你必须给它多一个空间,像这样:
char message[14];
//^^ See here 13 from 'Hello, world!' + 1 to determinate the string with a '\0'
它还必须有空间来保存一个'\0'来确定字符串
别忘了包含
#include <string.h> //For 'strcpy()'
#include <conio.h> //For 'getch()'
示例输出:
Repeat how many times? 5
0 - Hello, world!
1 - Hello, world!
2 - Hello, world!
3 - Hello, world!
4 - Hello, world!
关于c - 是什么导致了 c 中 printf 命令的这种奇怪输出,我该如何阻止它发生?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28775055/