I'm trying to create a program according to the prompt below but I keep recieving a Caught std::exception, what(): basic_string::at: __n (which is 0) >= this->size() (which is 0)
error, I though I was solid at C++ but I guess time takes its toll. My code is down below. Basically, first I parse the string by space character and save them in a vector<string>
after that I check if a word is larger than 5 and reverse it if it is and do nothing if it is not. If it isn't the final word, I add a space at the end. Bing bang boom, prompt complete, or at least I thought.
std::string spinWords(const std::string &str)
{
std::vector<std::string> words;
std::string spinnedWord;
int count = 0;
for(unsigned int i = 0; i < str.length(); i++)
{
char currentChar = str.at(i);
if (currentChar == ' ')
{
count++;
continue;
}
else if((int)words.size() == count)
{
words.push_back(¤tChar);
}
else
{
words[count] += currentChar;
}
}
for(unsigned int i = 0; i < words.size(); i++)
{
if(words[i].size() >= 5)
{
for (unsigned int j = words[i].length() - 1; j >= 0; j--)
{
spinnedWord += words[j].at(i);
}
}
if(i + 1 != words.size())
{
spinnedWord += ' ';
}
}
return spinnedWord;
}// spinWords
Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present.
Edit1: I have changed words[j].at(i);
to words[i].at(j);
and I have changed words.push_back(¤tChar);
to words.push_back(std::string(1, currentChar));
From what I currently understand, when I was pushing back ¤tChar
, I was causing a undefined behavior. I'll look into how to avoid that in the future. However, the error from before is still present, so the question remains unanswered
for (unsigned int j = words[i].length() - 1; j >= 0; j--)
{
spinnedWord += words[j].at(i);
}
You swapped j
an i
here. It must be words[i].at(j)
. Also j
probably shouldn't be unsigned here, because the loop condition j >= 0
is always true for unsigned integers.
EDIT: the UB concern for line words.push_back(¤tChar)
is valid too. The way to fix it is to construct a string from a char
explicitly:
words.push_back(std::string(1, currentChar));