How do i count punctuations??

I am new to C++ so kinda need help.
How do i count all the punctuations from a file??
These are the symbols in the file: ..;;??
.,.,.,?::: .

and this is the given code, but i dont know what to fill in..
Thanks a bunch!
---------------------------
int main ()
{
ifstream inData;
char symbol;
int periodCt = 0;
int commaCt = 0;
int questionCt = 0;
int colonCt = 0;
int semicolonCt = 0;
inData.open("switch.dat");
/* FILL IN */
return 0;
}
You can read each line then you use std::count.
1
2
3
4
5
6
7
8
9
10
11
std::string myString;
inData.open("switch.dat");

while(getline(inData, myString))
{
    periodCt += std::count(myString.begin(), myString.end(), '.');
    commaCt += std::count(myString.begin(), myString.end(), ',');
    questionCt += std::count(myString.begin(), myString.end(), '?');
    colonCt += std::count(myString.begin(), myString.end(), ':');
    semicolonCt += std::count(myString.begin(), myString.end(), ';');
}


It is actually quite simple if you give it a try.
Last edited on
When you read a file you can read chars, words, lines.
Assuming you read a string from a file called line.

1
2
3
4
5
		for (int i =0; i < line.size();i++)
			{
				if ((line[i]=='.') || (line[i]==',')|| (line[i]=='!')|| (line[i]=='?'))
					{cout << count << " " << line[i] << endl;}
			}

Alternatively, you could use ispunct().
http://www.cplusplus.com/reference/cctype/ispunct/

Also, there are a whole bunch of useful algorithms you can use. In this scenario, consider count_if().
http://www.cplusplus.com/reference/algorithm/count_if/
You can also use std::count to count punctuations quickly. See my example above.

@integralfx
std::count_if is actually longer and more cumbersome that std::count, even if the OP knows how to use lambda functions.
Last edited on

std::count_if is actually longer and more cumbersome that std::count, even if the OP knows how to use lambda functions.


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
#include <algorithm>
#include <cctype>
#include <chrono>
#include <iostream>
#include <string>

using sys_clock = std::chrono::system_clock;

int main()
{
    const std::string str{
        R"("Beware the Jabberwock, my son!
        The jaws that bite, the claws that catch!
        Beware the Jubjub bird, and shun
        The frumious Bandersnatch!")"
    };
    
    double t_count_if{};
    {
        std::cout << "--- count_if() ---\n";
        
        std::size_t count{};
        
        auto start = sys_clock::now( );
        count = std::count_if( str.begin( ), str.end( ), ispunct );
        auto end = sys_clock::now( );
        t_count_if = std::chrono::duration_cast< std::chrono::duration<double, std::micro> >( end - start ).count( );
        
        std::cout << "punctuation count = " << count << "\n";
        std::cout << "elapsed: " << t_count_if << " microseconds\n\n";
    }
    
    double t_count{};
    {
        std::cout << "--- count() ---\n";
        
        std::size_t count{};
        
        auto start = sys_clock::now( );
        count += std::count( str.begin( ), str.end( ), '.' );
        count += std::count( str.begin( ), str.end( ), ',' );
        count += std::count( str.begin( ), str.end( ), '!' );    // missed this one
        count += std::count( str.begin( ), str.end( ), '?' );
        count += std::count( str.begin( ), str.end( ), ':' );
        count += std::count( str.begin( ), str.end( ), ';' );
        auto end = sys_clock::now( );
        t_count = std::chrono::duration_cast< std::chrono::duration<double, std::micro> >( end - start ).count( );
        
        std::cout << "punctuation count = " << count << "\n";
        std::cout << "elapsed: " << t_count << " microseconds\n\n";
    }
    
    if( t_count_if < t_count )
        std::cout << "count_if() is faster by " << t_count - t_count_if << " microseconds\n";
    else
        std::cout << "count() is faster by " << t_count_if - t_count << " microseconds\n";

}


--- count_if() ---
punctuation count = 8
elapsed: 1.578 microseconds

--- count() ---
punctuation count = 6
elapsed: 0.76 microseconds

count() is faster by 0.818 microseconds

What was that again? count_if() is actually more cumbersome? Please.
Wow! count() is faster than count_if() by a whole 0.818 microseconds!!! I can definitely see some real world performance gains, especially after typing the same code six times.

edit: Realised I forgot to count the apostrophes as well. Another reason why count_if() is less cumbersome.
http://rextester.com/OLPGS67978
-> count_if() is faster than count() by about 2 microseconds.
Last edited on
@integralfx
Remember that the OP needs to count separate punctuations one by one. You can't just universally use std::count_if for all cases like that.

Thus, to write this :
count = std::count_if( str.begin( ), str.end( ), ispunct );
Actually to be honest, this line does not make much sense especially if you ask me.

Remember that the OP needs to count separate punctuations one by one. You can't just universally use std::count_if for all cases like that.

Second line of OP:
How do i count all the punctuations from a file??



Thus, to write this :
count = std::count_if( str.begin( ), str.end( ), ispunct );
Actually to be honest, this line does not make much sense especially if you ask me.

No, it is more than clear. If you have any problems about it, go back to study C++ for a few more months until you understand this simple homework assignment piece of code.

Can't tell if SakurasouBusters is trolling or just has an inflated ego. Wouldn't be surprised if both.
Last edited on
@integralfx
We should focus on giving the OP the solution he/she wants. If we use your solution, these lines may not be needed.
1
2
3
4
5
int periodCt = 0;
int commaCt = 0;
int questionCt = 0;
int colonCt = 0;
int semicolonCt = 0;


Fourth line of OP :
...and this is the given code, but i don't know what to fill in..

No, it is more than clear. If you have any problems about it, go back to study C++ for a few more months until you understand this simple homework assignment.
Can't tell if SakurasouBusters is trolling or just has an inflated ego. Wouldn't be surprised if both.

Most trolls have a weird mix of and inflated ego and self-esteem issues. That includes the ones who keep coming back over and over under different names.
MikeyBoy wrote:
Most trolls have a weird mix of and inflated ego and self-esteem issues. That includes the ones who keep coming back over and over under different names.

Remember that I have won the game. To be frank, you outsider have no position to meddle in our affair unnecessarily by making the situation worse.
closed account (48T7M4Gy)
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
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    char letter;
    
    int periodCt = 0;
    int commaCt = 0;
    int questionCt = 0;
    int colonCt = 0;
    int semicolonCt = 0;
    
    ifstream inFile;                     //open and check for error
    inFile.open("data.dat");
    if (inFile.fail())
    {
        cerr << "Error opening file" << endl;
        exit(1);
    }
    
    while (inFile >> letter)
    {
        switch (letter)
        {
            case '.':
                periodCt++;
            case ',':
                commaCt++;
            case '?':
                questionCt++;
            case ':':
                colonCt++;
            case ';':
                semicolonCt++;
            break;
        }
    }
    cout << "No. of periods " << periodCt << endl;
    cout << "No. of commas " << commaCt << endl;
    
    return 0;
}


Here's a start to a simple solution. You'll need to change the file name etc to suit and extend the print out.
The line 21 could/should read return 1;
The execution is still in the main() and thus the "mere" return takes us out from the program.

The exit() would be necessary if one desires quick end from any other function. However, in those cases one should strive for return to caller, which in turn should detect and handle (or pass) the error all the way to main(), which then ultimately returns.
Topic archived. No new replies allowed.