3

入力文字列を入力すると、プログラムが動かなくなります。プログラムの他のすべてのブランチをテストしたので、問題はここにあります。

注: 無限ループは意図的なものであり、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

4 に答える 4

2

他の人がすでに指摘しているように、無限ループがあります。通常、文字列検索ループは次の形式で表示されます。

int found = 0; 
while ((found = text.find(".", found )) != string::npos) {
    //...
}
于 2013-09-18T16:15:10.297 に答える
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) に設定しているため、次の反復でまったく同じ検索を再度実行しています。

于 2013-09-18T16:25:44.463 に答える
1

編集:気にしないでください、私の答えは間違っています。std::npos が -1 に設定された定数であることを知りませんでした。

この線: if ((text.find("." , j)) < 0 )

true になることはないため、ブレークは実行されません。

std::string.find()std::nposテキストが見つからない場合は、0 未満の値ではなく を返します。

参照: std::string.find()

于 2013-09-18T16:38:02.193 に答える
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;
}
于 2013-09-18T20:35:03.580 に答える