由于某种原因导致循环卡住的简单程序

时间:2013-09-18 16:08:52

标签: c++ string for-loop

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

注意:无限循环是有意的,应该由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); 
   }
  }
}

4 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:2)

这是因为您永远不会删除.,因此您永远不会输入您的第一个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),所以在你的下一次迭代中,你再次进行完全相同的搜索。

答案 2 :(得分:1)

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

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

永远不会是真的,因此永远不会执行。

如果找不到文字,

std::string.find()会返回std::npos,而不会返回小于0的值。

请参阅:std::string.find()

答案 3 :(得分:0)

我知道你想坚持你的代码,然而,真的非常糟糕,我讨厌你学习坏习惯。

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

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

#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;
}