【发布时间】:2021-11-07 21:22:57
【问题描述】:
我用 C 编写了一个代码来打印员工的身份证号(可以是数字和字母的组合)。 编译器将 id 号作为输入,但它不打印任何内容。起初,我使用'printf',但它不起作用,所以我用谷歌搜索最终发现在许多系统中出于性能原因有时会缓冲输出。我在以下一些线程中得到了许多可能的答案-
- simple c program not printing output
- Why does printf not flush after the call unless a newline is in the format string?
- printf not printing on console
但是,我尝试了所有可能性(作为初学者,实施可能是错误的),但没有一个适合我 [以 cmets 的形式给出]。我有如下代码。任何帮助表示赞赏。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int* ptr;
int m;
char n;
printf("Id number of employee 1:\n");
printf("Enter your id number length\n");
scanf("%d", &m);
printf("%d\n", m);
ptr = (int*) malloc (m *sizeof(int));
printf("Enter your id number:\n");
scanf("%s", &n);
// fflush( stdout );
// fprintf(stderr, "The id number of emploee 1 is %s", n);
// setbuf(stdout, NULL);
// setvbuf(stdout, NULL, _IONBF, 0);
// setvbuf (stdout, NULL, _IONBF, BUFSIZ);
// printf("The id number of employee 1 is %s\n", n);
printf("The id number of employee 1 is %s", n);
return 0;
}
【问题讨论】:
-
单个字符不能容纳多个字母。
-
您已经分配了
ptr,但随后使用了n,它是单个字符。而ptr需要存储char而不是int。所以应该是char *ptr = malloc(m); scanf("%s", ptr); printf("%s", ptr); -
如果
m代表id长度,其实应该是malloc(m+1)。字符串 NUL 终止符需要一个额外的字节。 -
你没有检查
malloc()是否成功;您没有检查scanf()是否成功。虽然它们不太可能失败,但当出现问题时,您需要添加缺失的错误检查以查看这是否导致部分问题。 -
@kaylum 感谢您的回答。我可以意识到我的错,我应该使用 char 而不是 int 并且你的答案得到了解决。当我给出长度时还有一个困惑,实际上它没有效果,即如果我给出 m = 5 之后我给出超过 5 个字符或少于 5 个字符,它会打印整个输入。如何将其修复为 m 值?