Time Limit Exceeded

I am finding and counting the last word from text file, it seems to be working on codeblocks but when running on mooshak it says time limit exceeded. Also when the text file has numbers like seven zeros it only counts six of them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
  #include<fstream>
#include<iostream>
#include<string>
#include<sstream>
#include<algorithm>
using namespace std;

int main()
{
    ifstream inFile;
    stringstream buffer;
    string fileName;
    string test;
    string word;
    string words;
    int counter = 0;

    cin >> fileName;

    inFile.open(fileName.c_str());
    if(inFile.fail())
    {
        return 0;
    }

    while(!inFile.eof())
    {
        inFile >> word;
    }
    inFile.close();

    word.erase(std::remove(word.begin(), word.end(), '.'), word.end());
    word.erase(std::remove(word.begin(), word.end(), ','), word.end());
    word.erase(std::remove(word.begin(), word.end(), '!'), word.end());
    word.erase(std::remove(word.begin(), word.end(), '?'), word.end());
    word.find_last_of(" ");
                      
    inFile.open(fileName.c_str());
    while(!inFile.eof())
    {
        buffer << inFile.rdbuf();
        test = buffer.str();

        getline(inFile, words);
    }
    inFile.close();

    int unsigned pos = 0;
    while(true)
    {

        pos =  test.find(word, ++pos);
        if (pos != std::string::npos)
        {
            counter++;
        }
        else break;
    }

    cout << word << ' ' << counter;
    return 0;
}

Last edited on
What are the assignment requirements?

Opening a textfile from userinput, find the last word from the file and count the occurance of that word.
And also if last word is a number then count the occurance of that number in the file
Please post a small sample of the input file.

But this seems to point me to a possible problem area:

main.cpp||In function ‘int main()’:|
main.cpp|53|warning: comparison is always true due to limited range of data type [-Wtype-limits]|
||=== Build finished: 0 errors, 1 warnings (0 minutes, 1 seconds) ===|


std::string::pos is a size_t, not an unsigned int. A size_t is a implementation defined unsigned type, but not necessarily an unsigned int. On my system, for example, it is a larger type, probably an unsigned long. You should use a size_t for functions that return this type to avoid this type of problem.
Last edited on
For example this text file: This is what Mississippi is.
The output is: is 5
Thank you! It works now with words.
But when counting numbers it seems to miss one number. For example the text file with seven zeros: 0000000
The output is 0 6
And works now with numbers, thank you!
Topic archived. No new replies allowed.