无法找到句子的开头

时间:2018-03-05 18:00:51

标签: c++ fstream

我需要从文件中找到具有最多字符数的句子,但我无法找到开始句子的索引( 我知道我的问题出在本部分

(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;


}

2 个答案:

答案 0 :(得分: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 :(得分:1)

更改此

endSentenses = index;
startSentensec = newIndex;

到这个

startSentensec = endSentenses + 1;
endSentenses = index;

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

您还应该更改

int endSentenses = 0;

int endSentenses = -1;

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