九穗禾 2019-09-04 21:04 采纳率: 60%
浏览 179
已采纳

为什么只有在直接打印一次字符串后,控制台才会显示调用函数打印的数组字符串

这是正常代码,但打印不出来

#include <iostream>
using namespace std;

int i = 0;
void show(const char* str, int sth = 0);

int main()
{
    char str[20] = "hello again,world!";
    show(str);
    show(str,2);
    return 0;
}

void show(const char* str, int sth)
{
    i++;
    if(sth == 0)
    {
        cout << str << endl;
    }
    else
    {
        for(int n=i; n>0; n--)
        {
            cout << str << endl;
        }
    }
}

打印结果如图图片说明

这是加了一个直接打印字符串的代码后

#include <iostream>
using namespace std;

int i = 0;
void show(const char* str, int sth = 0);

int main()
{
    char str[20] = "hello again,world!";
    show(str);
    show(str,2);
    return 0;
}

void show(const char* str, int sth)
{
    cout << "??什么问题??";
    i++;
    if(sth == 0)
    {
        cout << str << endl;
    }
    else
    {
        for(int n=i; n>0; n--)
        {
            cout << str << endl;
        }
    }
}

打印结果如图图片说明

在函数定义时把默认值也加入后,编译器就会检测出错误,如图:
图片说明
错误
图片说明

  • 写回答

1条回答 默认 最新

  • threenewbee 2019-09-05 00:27
    关注

    void show(const char* str, int sth)
    ->
    void show(const char* str, int sth = 0)
    否则sth是随机值,特别是可能是负数

    导致无法输出

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?