Urgent!!!

Write a C++ program to count the number of words ending with 's' from the text file India.txt.
closed account (LA48b7Xj)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    fstream fin("india.txt");

    if(!fin)
        return 1;

    int num_s = 0;

    string word;
    while(fin >> word)
        if(word.back() == 's')
            ++num_s;

    cout << "found " << num_s << " words ending in s" << endl;
}

This is my *slightly* complicated Non-C++11 approach:
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
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
    fstream indiaFile("india.txt");
    if(!indiaFile.is_open()) //File not open, not much we can do.
        return -1;

    string fileContents="";
    int wordsWithS=0;


    //Reads file.
    string inLine=""; //Will be changed by reading the file.
    while( getline(indiaFile, inLine))
    {
        indiaFile >> inLine;
        fileContents+=inLine;
    }

    //Parses file contents.
    int pos1=0; //Position data for substr().
    for(int i=0; i != fileContents.length(); i++)
    {
        if(fileContents[i] == ' ' || fileContents[i] == '\n' || i == fileContents.length()-1) //Found a Separator Character.
        {
            string word="";
            if(pos1 == 0)
                word=fileContents.substr(pos1, i);
            if(pos1 > 0)
            {
                word=fileContents.substr(pos1, i).erase(0,1); //Removes the beginning space/Char.
                if((fileContents.length()-1)-i > 0) //If not last word (Found by positioning of i and the length of FileContents), erase last Chars
                    word=word.erase((i-pos1)-1, word.length()); //Erases last Chars to 'capture' only the needed word and not any other bits.
            }
            cout <<"Found word: "<<word<<"\n";

            if(word[word.length()-1] == 's') //Found a word, increase the counter.
                wordsWithS++;
            
            pos1=i; //Updates position in For loop.
        }
    }
    cout <<"Words ending with S: "<<wordsWithS; //Display results.
}
why are you guys doing this guy's homework for him?
It seems some kids don't read the rules.

http://www.cplusplus.com/forum/beginner/1/

Topic archived. No new replies allowed.