涉及循环的简单程序由于某种原因卡住

Simple program involving a loop getting stuck for some reason

本文关键字:由于某种原因 程序 简单 循环      更新时间:2023-10-16

当我输入输入字符串时,程序卡住了。 我已经测试了程序中的所有其他分支,所以问题就在这里。

注意:无限循环是有意的,应该通过 break 语句来打破。

for (i = 0 ;  i >= 0 ; i++)
{
  text.append("kk");
  if ((text.find("." , j)) < 0 )
  {
     text.erase(text.size() - 2, 2);
     text2.append(text);
     writer << text2 << endl;
     text2.clear();
     j = 0;
     break;
  }
  else
  {
     j = text.find("." , j) + 1; 
     k = j + 1;
     letter = static_cast <int> ( text.at(k) );
     if (( letter < 123 ) && ( letter > 96 ))
     {
       letter = (letter - 32);
       (text.at(k)) = static_cast <char> (letter);
       text.erase(text.size() - 1, 2);
     }
   else 
   {
     text.erase(text.size() - 1, 2); 
   }
  }
}

正如其他人已经指出的那样,你有一个无限循环。我通常会看到以下格式的字符串查找循环。

int found = 0; 
while ((found = text.find(".", found )) != string::npos) {
    //...
}

这是因为您永远不会擦除.,因此您永远不会输入第一个if条件(带有中断的条件)。

你的逻辑是这样的:

Append "kk" to the string
If you don't find a '.'
  exit
Else
  If the second letter after the '.' is lower case
    Change it to upper case
    Delete the last letter in the string
  Else
    Delete the last letter in the string

然后你再次循环

假设您的字符串是:zzz.abcd您的迭代将是:

zzz.aBcdk
zzz.aBcdkk
zzz.aBcdkkk

等。。

这是造成最大伤害的线路:

j = text.find("." , j) + 1;

在这里,如果您没有找到".",则将 j 设置为 0 (-1 + 1),因此在下一次迭代中,您将再次执行完全相同的搜索。

编辑:没关系,我的答案是错误的。我不知道 std::npos 是一个常量设置为 -1。

该行: if ((text.find("." , j)) < 0 )

永远不会是真的,所以中断永远不会被执行。

如果未找到文本,std::string.find() 将返回 std::npos ,而不是小于 0 的值。

参见: std::string.find()

我知道你想坚持你的代码,但是,这真的很糟糕,我讨厌你学习坏习惯。

有时,甚至大多数时候,我们作为开发人员必须能够从代码示例中学习。我知道你不想使用任何你不理解的代码结构。但是,在大学和工作中,您将不得不从您不理解的代码中学习。这是提高技能和知识的好方法。

我写了一些代码来解决你的问题。这可能不是最好的解决方案。它经过测试并有效。请查看此代码并询问您是否不了解任何内容。希望这对您有价值。

#include <string>
#include <cctype>
void ToUpper( std::string& text, int position );
void ToUpper( std::string& text, int position )
{
    char c;
    c = text.at(position);
    text.at(position) = std::toupper(c);
    return;
}

int main(int argc, char *argv[])
{
    std::string text = "this is. a very simple. example. ok.";
    int found = 0;
    //Handle first character of sentence
    if ((found = text.find_first_not_of(" ", 0)) != std::string::npos)
    {
        ToUpper( text, found );     
    }
    while ((found = text.find(".", found )) != std::string::npos)
    {
        found = text.find_first_not_of(" .", found);
        if( found != std::string::npos )
        {
            ToUpper( text, found );
        }
    }
    return 0;
}