0

I have been trying to write a program which counts contents of a file in c++, I have used Ascii table and if statements to define characters, sentences but I not sure how I define words. there is also another problem with the code, it counts the last characters of the file twice and I have been trying to fix this issues by setting the "count = -1" but didn't turn out to be a good idea. any help will really appreciate it.

#include <iostream>
#include <fstream>  

using namespace std;


int main()
{


ifstream infile;
infile.open("cpp.txt");
int count = 0; // counting characters
int count_t = 0; // text objects
int count_s = 0; // sentence count
int count_i_s = 0; // e-sentence
int count_in_s = 0; // question count
char C;
//char word[30];




while (!infile.eof())
{
    infile.read(&C, 1);

    {
        // counting characters
        if (C >= ' '&& C <= '~'|| C == '\t' || C == '\n')
            count++;

    }
    //{
    //  infile << word;
    //  count_w++;
    //}

    {
        //counting sentances
        if (C == '.'|| C == '!'|| C == '?')
            count_s++;
    }
    {
        //counting exclamatory sentance
        if (C == '!')
            count_i_s++;
    }
    {
        //counting question sentances
        if (C == '?')
            count_in_s++;
    }

    {
        //counting text objector
        if (C == ' '|| C == '\t'|| C == '\n')
            count_t++;
    }





}



cout << "the number of charaters :" << count << endl;
cout << "the number of sentances :" << count_s << endl;
cout << "the number of exclamtory sentances :" << count_i_s << endl;
cout << "the number of interrogative sentances :" << count_in_s << endl;
cout << "the number of text objects :" << count_t << endl;




return 0;
}
  • 1
    Don't use numbers such as 33, 63, 126, etc. Use the character code directly, '.', 'a', '0', 'z', etc. – PaulMcKenzie Jan 05 '17 at 16:48
  • I did that but it's still counting the end of file (EOF) character twice. example if have a sentence at the end, it will count that two times. – Abrar Sajjad Jan 05 '17 at 17:03
  • You can replace `C == 9` with `C == '\t'` and `C == `0` with `C == '\n'`. – Thomas Matthews Jan 05 '17 at 17:17
  • 2
    Also, see [Why is iostream::eof inside a loop condition considered wrong?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). – Thomas Matthews Jan 05 '17 at 17:19
  • You can eliminate the `{` and `}` *outside* of the `if` statements. In your context, creating new substatements does not generate any benefits (like allowing local variables). – Thomas Matthews Jan 05 '17 at 17:21

0 Answers0