Welcome to Dream.In.Code
Become a C++ Expert!

Join 137,228 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,916 people online right now. Registration is fast and FREE... Join Now!




count characters

 
Reply to this topicStart new topic

count characters, count occurrences of char in file

rizwans
12 Mar, 2007 - 10:38 PM
Post #1

New D.I.C Head
*

Joined: 26 Oct, 2005
Posts: 25


My Contributions
Hi All

I got another coding problem. Hopefully someone can help. It does seem pretty easy but why i can't figure it out, I don't know.

Problem: Read in a file. Count the number of occurences of each letter in file. Ignore newline, tab, integers, etc...

I can't use any helper functions or anything of the sort.

Example:

Here is the file. how many.

h - 2
e - 4
r - 1
, etc..


[code]

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
ifstream inputfile;
int count = 0;
int length;
char ch;

inputfile.open("text.txt", ios::in)

if (inputfile.fail())
{
cout << "error - bailing out";
}

if (count > length)
{
count = 0;
}

inputfile.get(ch);
if (ch >= 'A' && ch <= 'Z')
{
ch -= 'A' - 'a'; //convert from upper to lowercase
}
if (ch == 'a' || 'A')
{
ch++;
count++;
cout << count << "-" << ch << endl;
}

inputfile.close();
return 0;
}










User is offlineProfile CardPM
+Quote Post

AmitTheInfinity
RE: Count Characters
12 Mar, 2007 - 10:47 PM
Post #2

C Surfing ∞
Group Icon

Joined: 25 Jan, 2007
Posts: 1,026



Thanked: 35 times
Dream Kudos: 125
My Contributions
QUOTE(rizwans @ 13 Mar, 2007 - 12:08 PM) *

Hi All

I got another coding problem. Hopefully someone can help. It does seem pretty easy but why i can't figure it out, I don't know.

Problem: Read in a file. Count the number of occurences of each letter in file. Ignore newline, tab, integers, etc...

I can't use any helper functions or anything of the sort.

Example:

Here is the file. how many.

h - 2
e - 4
r - 1
, etc..


CODE


#include <iostream>
#include <fstream>
using namespace std;

int main()
{
ifstream inputfile;
int count = 0;
int length;
char ch;

inputfile.open("text.txt", ios::in)

if (inputfile.fail())
{
cout << "error - bailing out";
}

if (count > length)
{
count = 0;
}

inputfile.get(ch);
if (ch >= 'A' && ch <= 'Z')
{
ch -= 'A' - 'a';           //convert from upper to lowercase
}
if (ch == 'a' || 'A')
{
ch++;
count++;
cout << count << "-" << ch << endl;
}

inputfile.close();
return 0;
}



well you can have array to store counts for each character.
finalise which characters you want to count [only alphanumerics or punctuations also], then make that much bit integer array. initialise it to zero.

Now you can have a simple switch case where you will compare every letter from file to some charater and increment the count for that character in your array.

e.g if arr[1] location is for 'b' / 'B' then whenever it occurs you will increment arr[1]. right?

Hope this will help you. smile.gif

(ya and when you use [code ] tag please use [/code ] also to finish it biggrin.gif )
User is offlineProfile CardPM
+Quote Post

rizwans
RE: Count Characters
14 Mar, 2007 - 12:34 AM
Post #3

New D.I.C Head
*

Joined: 26 Oct, 2005
Posts: 25


My Contributions
thanks for the tip
i read the question wrong again.
i have to use a struct in the program

So far I can increment the count and output the first letter of the file but the part that i'm confused on is reading the entire file or even just the first line. I need to read that in then count the occurrences of each letter in that line.
see example above.
I tried using inputfile.getline(ch)
but that didn't work at all. gave crazy errors.
not too sure how to do it for the entire line.
somebody help.
have to translate this to assembly language after c++ version.



[/code]
#include <iostream>
#include <fstream>

using namespace std;

#define NUM_LETTERS 26

struct Letter_Stats
{
bool some_upper;
int count;
};

Letter_Stats stats[NUM_LETTERS]; //this is the actual array declaration
int main()
{
char ch;
ifstream inputfile;
int length = 0;
Letter_Stats upper; //uppper character defined here
Letter_Stats newcount;

inputfile.open("text.txt", ios::in);

if (inputfile.fail())
{
cout << "error - bailing out";
}

if (newcount.count > length)
{
newcount.count = 0;
}
inputfile.get(ch);
//if upper character present
//user informed
//counter increments

if (ch >= 'A' && ch <= 'Z')
{
upper.some_upper = false;
newcount.count++;
}
if (ch >= 'a' && ch <= 'z')
{
newcount.count++;
}
//display the actual output
{
cout << newcount.count << "-" << ch << endl;
}


inputfile.close();
return 0;
}

User is offlineProfile CardPM
+Quote Post

AmitTheInfinity
RE: Count Characters
14 Mar, 2007 - 01:07 AM
Post #4

C Surfing ∞
Group Icon

Joined: 25 Jan, 2007
Posts: 1,026



Thanked: 35 times
Dream Kudos: 125
My Contributions
well it seems that you did not get the problem 100%. It says...

QUOTE

Problem: Read in a file. Count the number of occurences of each letter in file. Ignore newline, tab, integers, etc...

I can't use any helper functions or anything of the sort.

Example:

Here is the file. how many.

h - 2
e - 4
r - 1
, etc..


and now you have a structure associated with it. blink.gif
Please understand that you need to show count for every character from a - z so you will need 26 structure variables to store their counts.

so you can have a structure like

CODE

struct counts
{
  char ch;
  int count;
};


now have an array of structures like

CODE

counts char_struct[26] //as there are 26 alphabets.


and initialise ch of this structures in a for loop to get

CODE

char_struct[0].ch='a'; char_struct[1].ch='b'; //and so on till z.


now get the character from file one by one till file ends and have a switch like
[ use while loop on "infile". Something like : while(!infile.eof()) ]

CODE

switch(ch)
{
  case 'a' :
  case 'A' : char_struct[0].count++; break;
  case 'b' :
  case 'B' : char_struct[1].count++; break;

//like this till z
}


try this and tell me whether you got it... smile.gif

ya and you have to put code in between the tags like

[code ]
//code goes here
[/code ]

then it shows it like [I just removed that extra space there]

CODE

//code goes here

User is offlineProfile CardPM
+Quote Post

rizwans
RE: Count Characters
14 Mar, 2007 - 01:19 AM
Post #5

New D.I.C Head
*

Joined: 26 Oct, 2005
Posts: 25


My Contributions
k cool thanks man
i'll try it out and let you know
User is offlineProfile CardPM
+Quote Post

rizwans
RE: Count Characters
14 Mar, 2007 - 02:08 AM
Post #6

New D.I.C Head
*

Joined: 26 Oct, 2005
Posts: 25


My Contributions
i just used a few characters to test it out

[/code]
File Edit Options Buffers Tools C++ Help
#include <iostream>
#include <fstream>

using namespace std;

#define NUM_LETTERS 5

struct Letter_Stats
{
bool some_upper;
int count;
char ch;
};

int main()
{
ifstream inputfile;
char ch;
Letter_Stats stats[5];

inputfile.open("text.txt", ios::in);

if (inputfile.fail())
{
cout << "error - bailing out";
}
inputfile.get(ch);
// for (stats[26].count = 0; stats[26].count < 26; stats[26].count++)

for(stats[0].ch = 'a'); (stats[1].ch = 'b'); (stats[2].ch = 'c'); (stats[3].ch = 'd'); (stats[4].ch = 'e')
cout << stats[5].count << "-" << ch << endl;


inputfile.close();
return 0;
}


[/code]

it didn't work. it says:
newassign5.cpp:29: syntax error before `)' token
newassign5.cpp:29: syntax error before `;' token
newassign5.cpp:30: syntax error before `<<' token

plus we also have to take into consideration that the struct that i'm using doesn't have

char ch

we would only get the ch input from
inputfile.get(ch)

Also when i did this, it worked for the count but don't know how to do for characters.
for (stats[26].count = 0; stats[26].count < 26; stats[26].count++)

User is offlineProfile CardPM
+Quote Post

rizwans
RE: Count Characters
14 Mar, 2007 - 03:42 AM
Post #7

New D.I.C Head
*

Joined: 26 Oct, 2005
Posts: 25


My Contributions
ok here's some new stuff
[/code]
#define NUM_LETTERS 26

struct Letter_Stats
{
bool some_upper;
int count;

};

int main()
{
ifstream inputfile;
char ch;
Letter_Stats stats[26];
Letter_Stats upper;

inputfile.open("text.txt", ios::in);

if (inputfile.fail())
{
cout << "error - bailing out";
}

// stats[26].count = 0;
for (stats[26].count = 0; stats[26].count < 26; stats[26].count++)
inputfile.get(ch);
while (!inputfile.eof())
{
inputfile.get(ch);

if (ch >= 'a' && ch <= 'z')
{
upper.some_upper = false;
stats[26].count--;
cout << stats[26].count << "-" << ch << endl;
}
}

inputfile.close();
return 0;
}

[/code]
i know that it can be done char by char 26 times
but the problem with that is the translation to assembly.
writing out 26 if statements is long and is prone to errors.
User is offlineProfile CardPM
+Quote Post

rizwans
RE: Count Characters
14 Mar, 2007 - 04:13 AM
Post #8

New D.I.C Head
*

Joined: 26 Oct, 2005
Posts: 25


My Contributions
i have tried everything and i can't get this at all.
i have tried for loops, individual if statements everything and it is not working.
please help me
this is due today at 10:00pm and i still have to translate it to assembly
which is going to be another task.

User is offlineProfile CardPM
+Quote Post

AmitTheInfinity
RE: Count Characters
14 Mar, 2007 - 05:17 AM
Post #9

C Surfing ∞
Group Icon

Joined: 25 Jan, 2007
Posts: 1,026



Thanked: 35 times
Dream Kudos: 125
My Contributions
QUOTE(rizwans @ 14 Mar, 2007 - 05:43 PM) *

i have tried everything and i can't get this at all.
i have tried for loops, individual if statements everything and it is not working.
please help me
this is due today at 10:00pm and i still have to translate it to assembly
which is going to be another task.


tell me one thing what exactly are you trying to count? because in problem you have shown that you need to count occurances of every character [case insensitive] and in code you are finding count of small case letters and count of upper case letters...

just clear the confusion and your job is done buddy, because that's the only problem I can see in your code, once you clear it then we will solve it in one go wink2.gif .

well, why do you have that boolean in your structure? mellow.gif
User is offlineProfile CardPM
+Quote Post

AmitTheInfinity
RE: Count Characters
14 Mar, 2007 - 05:47 AM
Post #10

C Surfing ∞
Group Icon

Joined: 25 Jan, 2007
Posts: 1,026



Thanked: 35 times
Dream Kudos: 125
My Contributions
Well, this is something I have tried with whatever I understood from the problem.

This program opens a file and counts occurances of characters [upper or lower doesn't matter]. Displays the characters occured 1 or more times.

CODE

#include<iostream.h>
#include<fstream.h>

#define NUM_LETTERS 26

// I have ch there to keep track of count i.e. which char has what count.
//check the last part of main where I am printing, you will get it.
struct Letter_Stats
{
    int count;
    char ch;
};

int main()
{
    ifstream inputfile;
    char ch;
    int i;
    Letter_Stats stats[NUM_LETTERS];
    inputfile.open("c:\\notepad.txt", ios::in);
    if (inputfile.fail())
    {
        cout << "error - bailing out";
        return 1;
    }
//initialize the array of structures
    for (i=0;i<NUM_LETTERS;i++)
    {
        stats[i].count=0;
        stats[i].ch=('a' + i);
    }
//do till file ends
    while (!inputfile.eof())
    {
        inputfile.get(ch);
//increment counter for appropriate character
        switch(ch)
        {
        case 'a' :
        case 'A' : stats[0].count++; break;
        case 'b' :
        case 'B' : stats[1].count++; break;
        case 'c' :
        case 'C' : stats[2].count++; break;
        case 'd' :
        case 'D' : stats[3].count++; break;    
        case 'e' :
        case 'E' : stats[4].count++; break;    
        case 'f' :
        case 'F' : stats[5].count++; break;    
        case 'g' :
        case 'G' : stats[6].count++; break;    
        case 'h' :
        case 'H' : stats[7].count++; break;    
        case 'i' :
        case 'I' : stats[8].count++; break;    
        case 'j' :
        case 'J' : stats[9].count++; break;    
        case 'k' :
        case 'K' : stats[10].count++; break;    
        case 'l' :
        case 'L' : stats[11].count++; break;    
        case 'm' :
        case 'M' : stats[12].count++; break;    
        case 'n' :
        case 'N' : stats[13].count++; break;    
        case 'o' :
        case 'O' : stats[14].count++; break;    
        case 'p' :
        case 'P' : stats[15].count++; break;    
        case 'q' :
        case 'Q' : stats[16].count++; break;    
        case 'r' :
        case 'R' : stats[17].count++; break;    
        case 's' :
        case 'S' : stats[18].count++; break;
        case 't' :
        case 'T' : stats[19].count++; break;    
        case 'u' :
        case 'U' : stats[20].count++; break;    
        case 'v' :
        case 'V' : stats[21].count++; break;    
        case 'w' :
        case 'W' : stats[22].count++; break;    
        case 'x' :
        case 'X' : stats[23].count++; break;    
        case 'y' :
        case 'Y' : stats[24].count++; break;    
        case 'z' :
        case 'Z' : stats[25].count++; break;    
        }
    }
    inputfile.close();
//print characters and count if it is more than 0
    for(i=0;i<NUM_LETTERS;i++)
    {
        if(stats[i].count>0)
        {
            cout<<stats[i].ch<<" occured "<<stats[i].count<<" times"<<endl;
        }
    }

    return 0;
}



Now to make is case sensitive you can have 2 such array and need to modify switch statement. [though it's not the good logic but for now... biggrin.gif ]

hope this will help you.

This post has been edited by AmitTheInfinity: 14 Mar, 2007 - 05:48 AM
User is offlineProfile CardPM
+Quote Post

msg555
RE: Count Characters
14 Mar, 2007 - 06:16 AM
Post #11

D.I.C Head
Group Icon

Joined: 4 May, 2006
Posts: 136



Thanked: 2 times
Dream Kudos: 25
My Contributions
instead of

CODE
inputfile.get(ch);
//increment counter for appropriate character
        switch(ch)
        {
        case 'a' :
        case 'A' : stats[0].count++; break;
        case 'b' :
        case 'B' : stats[1].count++; break;
        case 'c' :
        case 'C' : stats[2].count++; break;
        case 'd' :
        case 'D' : stats[3].count++; break;    
        case 'e' :
        case 'E' : stats[4].count++; break;    
        case 'f' :
        case 'F' : stats[5].count++; break;    
        case 'g' :
        case 'G' : stats[6].count++; break;    
        case 'h' :
        case 'H' : stats[7].count++; break;    
        case 'i' :
        case 'I' : stats[8].count++; break;    
        case 'j' :
        case 'J' : stats[9].count++; break;    
        case 'k' :
        case 'K' : stats[10].count++; break;    
        case 'l' :
        case 'L' : stats[11].count++; break;    
        case 'm' :
        case 'M' : stats[12].count++; break;    
        case 'n' :
        case 'N' : stats[13].count++; break;    
        case 'o' :
        case 'O' : stats[14].count++; break;    
        case 'p' :
        case 'P' : stats[15].count++; break;    
        case 'q' :
        case 'Q' : stats[16].count++; break;    
        case 'r' :
        case 'R' : stats[17].count++; break;    
        case 's' :
        case 'S' : stats[18].count++; break;
        case 't' :
        case 'T' : stats[19].count++; break;    
        case 'u' :
        case 'U' : stats[20].count++; break;    
        case 'v' :
        case 'V' : stats[21].count++; break;    
        case 'w' :
        case 'W' : stats[22].count++; break;    
        case 'x' :
        case 'X' : stats[23].count++; break;    
        case 'y' :
        case 'Y' : stats[24].count++; break;    
        case 'z' :
        case 'Z' : stats[25].count++; break;    
        }

How about
CODE
        inputfile.get(ch);
        //increment counter for appropriate character
        
        if('a' <= ch && ch <= 'z')
            stats[ch - 'a'].count++;
        else if('A' <= ch && ch <= 'Z')
            stats[ch - 'A'].count++;


This post has been edited by msg555: 14 Mar, 2007 - 06:17 AM
User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 12/4/08 02:55PM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month