【问题标题】:The value in the string array is overwritten and not completely replaced字符串数组中的值被覆盖而不是完全替换
【发布时间】:2021-05-16 16:33:24
【问题描述】:

当我执行“consoleinfo()”函数两次且第一个文本比第二个长时,数组中的值与第一个重叠

这是我的代码:

string last[20];

void consoleinfo(string log)
{
    arrayshift();
    last[18] = "[INFO] " + log;
    consolerefresh();
}

移动所有值:

void arrayshift()
{
    for (int i = 1; i < (sizeof(last) / sizeof(last[0])); i++)
    {
        last[i - 1] = last[i];
    }
}

打印last的所有值:

void consolerefresh()
{
    for (int i = 0; i < (sizeof(last) / sizeof(last[0])); i++)
    {
        std::cout << last[i] << std::endl;
    }
}

我的意见:

consoleinfo("Hello World!");
consoleinfo("Apple");

输出:

[INFO] Hello World!
[INFO] Apple World!

【问题讨论】:

标签: c++ arrays console-application


【解决方案1】:

恕我直言,这里打错了 last[18] = "[INFO] " + log;,必须是last[19] = "[INFO] " + log;

当你第一次输入时,你会进入控制台

[信息]你好世界!

当你第二次输入时,最后一行输出到上一个最后一行输出的地方,Hello这个词被改写成Apple这个词。

[INFO] 苹果世界!

您必须在输出前清理控制台或在最后一个文本中填充空格,直到控制台宽度或前一行宽度。如果您使用比 Hello 更长或更短的词,那将是显而易见的。

last[18] = "[INFO] " + log;
if (last[17].length() > last[18].length())
  last[18] += std::string(last[17].length() - last[18].length(), ' ');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-25
    • 1970-01-01
    • 2011-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多