【问题标题】:Output is not shown in C输出未在 C 中显示
【发布时间】:2020-07-23 15:29:12
【问题描述】:
char DayName(int day_th)
{
  const char *DayName[] = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday" };
  return *DayName[day_th];
}

int main()
{
  int day_th=2;
  printf("What is your favorite day of the week? 1 is Sunday and 7 is Saturday: \n");
  printf("Day %d is a %s", day_th, DayName(day_th-1));
  return 0;
}

我正在编写一个输出类似于“第 2 天是星期一”的代码。我正在使用 VS 2019,编译器不会引发任何错误。但是,当我点击运行时,只显示“你最喜欢哪一天...行”,而不显示“第 2 天是星期一”。请帮忙!非常感谢。

【问题讨论】:

  • 以换行符结束输出。
  • 打开编译器警告并听取它。

标签: c string pointers


【解决方案1】:

您通过将错误类型的数据传递给 printf 调用了未定义的行为char 被传递到预期 char* 的位置 (%s)。

函数DayName 应该返回数组const char* 的元素而不取消引用它们。

#include <stdio.h>

const char* DayName(int day_th)
{
  const char *DayName[] = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday" };
  return DayName[day_th];
}

int main()
{
  int day_th=2;
  printf("What is your favorite day of the week? 1 is Sunday and 7 is Saturday: \n");
  printf("Day %d is a %s", day_th, DayName(day_th-1));
  return 0;
}

【讨论】:

  • 很好,我认为这是“由于缺少 \n 而没有刷新标准输出”问题!
猜你喜欢
  • 1970-01-01
  • 2019-10-06
  • 1970-01-01
  • 2021-06-07
  • 1970-01-01
  • 2020-01-28
  • 2022-01-03
  • 1970-01-01
相关资源
最近更新 更多