【问题标题】:C++ Why i'm getting trailing whitespace in the output of this?C++ 为什么我在这个输出中得到尾随空格?
【发布时间】:2022-11-21 10:17:55
【问题描述】:

这是我一直在为这个 codewars 问题研究的解决方案:https://www.codewars.com/kata/56a5d994ac971f1ac500003e/cpp

我希望输出为"abigailtheta"。我在 vscode 上得到了正确的输出,当我从终端编译代码时也得到了正确的输出,但是 codewars 站点显示输出是 "abigail,这告诉我我的输出中有我没有的空白尾之前没看到(终端和 vscode 的输出没有字符串格式)。知道最后那个空白是从哪里来的吗?

#include <iostream>
#include <string>
#include <vector>
#include <numeric>

class LongestConsec
{
public:
    static std::string longestConsec(const std::vector<std::string> &strarr, int k)
    {
        std::string concChars{};
        std::string maxChars{};
        for (int i{}; i < strarr.size(); ++i)
        {
            concChars = strarr[i];
            for (int y{i + 1}; y < (i + k); ++y)
            {
                concChars += strarr[y];
            }
            maxChars = (maxChars.length() < concChars.length()) ? concChars : maxChars;
        }
        return maxChars;
    }
};


int main()
{
    LongestConsec a;
    std::vector<std::string> v{"zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"};
    std::cout << a.longestConsec(v, 2) << '\n';
    return 0;
}

【问题讨论】:

  • 抱歉,网站上的哪一部分显示了它的输出“abigail”?我看到“abigailtheta”

标签: c++


【解决方案1】:

我认为你的问题来自这里。

for (int y{i + 1}; y < (i + k); ++y)
{
     concChars += strarr[y];
}

如果i+k &gt;= strarr.size() 会发生什么?当y大于strarr.len()-1时,strarr[y]是什么?它可以是空格,或者一些陌生的字符,或者更好的是,它会使你的程序崩溃。

【讨论】:

    猜你喜欢
    • 2019-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 2013-10-04
    • 1970-01-01
    相关资源
    最近更新 更多