无法找到句子的开头

问题描述 投票:0回答:2

我需要从文件中找到具有最多字符数的句子,但我找不到用于启动句子的索引(我知道我的问题在于这部分

(if ((n == '?')||(n == '!')||(n == '.')) {
            newIndex = index;
}

但我不知道如何改进它。下面的部分是我的其余代码。

using namespace std;
int main()

{
    int newIndex = 0;
    int startSentensec = 0;
    int endSentenses = 0;
    int index = -1;
    int count = 0;
    const string wayToFile = " " ;
    int total = 0;
    char n;
    vector<char>MyVector;
    ifstream file(wayToFile);
    while (!file.eof())
    {
        file >> n;
        if (file.eof()) break;

        index += 1;
        MyVector.push_back(n);
         cout << n << " ";
       //123
        if ((n == '0' ) ||(n == '1' ) ||(n == '2' ) ||(n == '3' ) ||(n == '4' ) ||(n == '5' ) ||(n == '6' ) ||(n == '7' ) ||(n == '8' ) ||(n == '9' )) {
                                count += 1;
                                        }
        ///456
        if ((n == '?')||(n == '!')||(n == '.')) {
            newIndex = index;
            if (count >= total){

                    total = count;
                    endSentenses = index;
                    startSentensec =   newIndex ;
                    count = 0;

        }
        }
            }




    file.close();
    cout << endl<< "Sentences with the greatest number of digits :";
        for (int i = (startSentensec); i <= endSentenses; i++){
            cout << MyVector[i];
        }
    cout << endl;
    cout  << total << endl;


}
c++ fstream
2个回答
2
投票

这部分:

    if ((n == '?')||(n == '!')||(n == '.')) {
        newIndex = index;
        if (count >= total){

                total = count;
                endSentenses = index;
                startSentensec =   newIndex ;
                count = 0;
        }
    }

有一个重大问题。请参阅内联注释

    if ((n == '?')||(n == '!')||(n == '.')) {
        newIndex = index;   // Here newIndex is set to the same as index
        if (count >= total){

                total = count;
                endSentenses = index;          // So these two lines will make
                startSentensec =   newIndex ;  // endSentenses and startSentensec identical
                count = 0;
        }
    }

在检查新的最大值之前,请勿更新newIndex

喜欢:

    if ((n == '?')||(n == '!')||(n == '.')) {
        if (count >= total){

                total = count;
                endSentenses = index;
                startSentensec =   newIndex ;
                count = 0;
        }
        newIndex = index;
    }

关于一些改进 - 这个

    if ((n == '0' ) ||(n == '1' ) ||(n == '2' ) ||(n == '3' ) ||(n == '4' ) ||(n == '5' ) ||(n == '6' ) ||(n == '7' ) ||(n == '8' ) ||(n == '9' )) {
        count += 1;
    }

可以写

    if ((n >= '0' ) && (n <= '9' )) {
        count += 1;
    }

1
投票

改变这一点

endSentenses = index;
startSentensec = newIndex;

对此

startSentensec = endSentenses + 1;
endSentenses = index;

对我来说似乎是一种进步。换句话说,句子的开头是前一句末尾的一个句子。

你也应该改变

int endSentenses = 0;

int endSentenses = -1;

所以第一句话将从零指数开始。

© www.soinside.com 2019 - 2024. All rights reserved.