0

This is a solution i've been working on for this codewars problem: https://www.codewars.com/kata/56a5d994ac971f1ac500003e/cpp

I want the output to be "abigailtheta". I'm getting the correct output on vscode and the correct output when I compile the code from the terminal as well, but the codewars site shows that the output is "abigail which tells me that there is whitespace tail in my output that i didn't see before (the output from the terminal and vscode didn't have the strings format). Any idea where that whitespace in the end comes from?

#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;
}
  • sorry which part on the site shows it's output "abigail"? I'm seeing "abigailtheta" – Sin Han Jinn Nov 21 '22 at 01:54
  • @Han When i press the test option it is failing the first test which is the array with the abigail, etc, strings. Does it pass the test for you? The codewars looks straight at the output of the `longestConsec` function (i'm not including the `main()` function in the answer, i'm including it here because i tried it for debug reasons). Also, when i try the same code in this [online compiler](https://www.programiz.com/cpp-programming/online-compiler/) the answer is `abigail` with whitespace at the end. – DarkCloudsEverywhere Nov 21 '22 at 02:03
  • There's no good reason to write a class here. All you need is a function. If "codewars" insists on having a class it's teaching you bad habits. – Pete Becker Nov 21 '22 at 03:04

1 Answers1

1

I think your issue comes from here.

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

What happens if i+k >= strarr.size()? what is strarr[y] when y greater than strarr.len()-1? It can be whitespace, or some stranger character, or better, it crashes your program.

GAVD
  • 1,977
  • 3
  • 22
  • 40