簡體   English   中英

為什么這個程序返回最后一個單詞而不是最長的單詞?

[英]Why is this program returning the last word and not the longest word?

為什么這個程序返回垃圾值? 我希望輸出是“大”這個詞,但值實際上是“老鼠”——最后一個詞。

#include <iostream>
#include <string>
using namespace std;

std::string LongestWord(std::string sen)
{

    std::string s2, lW;
    for (int i = 0; i < sen.size(); ++i) {

        while (sen[i] != ' ') {
            s2 += sen[i];
            ++i;
        }
        if (s2.size() > lW.size()) {
            lW = ""; lW = s2;
        }

        s2 = "";
    }
    return lW;
}
int main(void)
{

    cout << LongestWord("a cat ate the large rat") << endl;
    return 0;

}

您的內部while循環幾乎肯定會超出給定string參數的末尾(除非末尾有空格)。 更改此內部循環以檢查該字符串的大小,如下所示:

        while (i < sen.size() && sen[i] != ' ') {
            s2 += sen[i];
            ++i;
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM