我正在尝试根据下面的提示创建一个程序,但我一直收到一个Caught std::exception, what(): basic_string::at: __n (which is 0) >= this->size() (which is 0)
错误,虽然我在 C++ 方面很扎实,但我想时间会付出代价。我的代码在下面。基本上,首先我通过空格字符解析字符串,然后将它们保存在 avector<string>
中,然后我检查一个单词是否大于 5,如果是则反转它,如果不是,则不执行任何操作。如果这不是最终话,我会在最后添加一个空格。砰砰砰,提示完成,至少我是这么想的。
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
编写一个函数,接收一个或多个单词的字符串,并返回相同的字符串,但所有五个或更多字母单词都颠倒了(就像这个 Kata 的名字一样)。传入的字符串将仅包含字母和空格。仅当存在多个单词时才会包含空格。
Edit1:我已更改words[j].at(i);
为words[i].at(j);
,我已更改words.push_back(¤tChar);
为words.push_back(std::string(1, currentChar));
据我目前的理解,当我推回时¤tChar
,我导致了一个未定义的行为。我会研究如何在未来避免这种情况。但是,之前的错误仍然存在,因此问题仍未得到解答