【问题标题】:printf in C does not giving any outputC中的printf没有给出任何输出
【发布时间】:2021-11-07 21:22:57
【问题描述】:

我用 C 编写了一个代码来打印员工的身份证号(可以是数字和字母的组合)编译器将 id 号作为输入,但它不打印任何内容。起初,我使用'printf',但它不起作用,所以我用谷歌搜索最终发现在许多系统中出于性能原因有时会缓冲输出。我在以下一些线程中得​​到了许多可能的答案-

但是,我尝试了所有可能性(作为初学者,实施可能是错误的),但没有一个适合我 [以 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 值?

标签: c gcc printf buffer flush


【解决方案1】:

正如评论部分所说的“单个字符不能容纳一串字母”。 这里还有其他东西可以制作更好的代码,例如释放分配的内存。 这是如何完成的代码示例:

int main()
{
     char* ptr;
     int m;

     printf("Id number of employee 1:\n");
     printf("Enter your id number length\n");
     scanf("%d", &m);

     ptr = (char*)malloc(m * sizeof(char) + 1);

     if (ptr == NULL) {
         printf("Allocation faild...");
         return 1;
         //you can call main to try again...
     }

     printf("Enter your id number:\n");
     scanf("%s", ptr);

     //scanf is not reliable, you can use a loop to enter all characters 
     //to the char array or validate scanf.
     

     printf("The id number of employee 1 is %s",ptr);
     // dont forget to free the allocated data

     free(ptr);
     
     return 0;
}

【讨论】:

    【解决方案2】:

    一种可行的解决方案是(没有动态内存分配)-

    直接把char n改成char n[m],不需要指针

    另一个可行的解决方案是(使用动态内存分配)-

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    int main()
    {
        int m = 5;
        printf("Id number of employee 1:\n");
        printf("Enter your id number length\n");
        scanf("%d", &m);
        char x[m];
        char *n = x;
        n=(char*)malloc(sizeof(char)*m);
        printf("Enter your id number:\n");
        scanf("%s", n);
        printf("The id number of employee 1 is %s\n", n);
        free(n);
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-17
      • 2021-02-07
      • 1970-01-01
      • 2019-08-21
      相关资源
      最近更新 更多