中断For循环C ++

问题描述 投票:-6回答:1

我有这个代码

#include <iostream>
#include <string> 

using namespace std;

int main() {
    string text, findstring, replacestring;
    int i = -1;
    cout << "Text eingeben: ";
    getline( cin, text ); 
    cout << "findstring: ";
    cin >> findstring; 
    cout << "replacestring: "; 
    cin >> replacestring;
    if( text.find( findstring, 0 ) == -1 ) {
        cout << "Fehler: findString ist nicht vorhanden" << endl;
        return 1;
    }
    cout << endl;
    for (i; i>text.length();++i) {
        i =    text.find( findstring, i+1 );

            cout << "String " << findstring << " gefunden an Pos: " << i << endl;
            text.replace( i, findstring.length(), replacestring );

    }
    cout << "Ergebnis: " << text << endl;
    cout << text.length();
    return 0;
}

在另一个字符串中搜索字符串并返回其位置并将其替换为另一个字符串。现在我的问题是,当目标字符串在原始字符串中被多次包含时,为什么这不起作用?我尝试使用do ... while循环,它工作得很好。我想知道如何使用for循环执行此操作。

c++ loops for-loop break
1个回答
0
投票

这有点棘手。这个错误是通过比较itext.length()引起的。 i是一个值为-1的int,而text.length()unsigned type,因此-1 is always > text.length()。这就是为什么你的for loop只运行一次(当i仍然是-1)。

这是一种可能的修复方法(在我的机器上运行良好):

#include <iostream> 
#include <string>

using namespace std;

int main() {
    string text, findstring, replacestring;
    int i = -1;

    cout << "Text eingeben: ";
    getline(cin, text);
    cout << "findstring: ";
    cin >> findstring;
    cout << "replacestring: ";
    cin >> replacestring;

    if( text.find( findstring, 0 ) == -1 ) {
        cout << "Fehler: findString ist nicht vorhanden" << endl;
        return 1;
    }

    cout << endl;

    do {
        i = text.find(findstring, i + 1);
        if (i == -1) {
            cout << "No more result found" << endl;
            break;
        } else {
            cout << "String " << findstring << " gefunden an Pos: " << i << endl;
            text.replace(i, findstring.length(), replacestring);
        }

    } while (true);
    cout << "Ergebnis: " << text << endl;
    cout << text.length() << endl;
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.