472,358 Members | 2,054 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,358 software developers and data experts.

Counting Words

Hi!

I'm writing a program that is supposed to read a line of input, count
the words and the number of occurrences of each letter. Then it should
prints the number of occurrences of each letter that appears in the
input line. For example, if I typed "I say Hi." it should give the
following output:

3 words
1 a
1 h
2 i
1 s
1 y

Here is my problem. If I type in a phrase like "I ask you, what is
truth? I get this:

7 words
257 a
512 h
257 i
1 k
1 o
256 r
257 s
768 t
257 u
256 w
1 y
Press any key to continue

Why am I getting this bad output? Can anyone see anything in my code
that would cause this. You should be able to put commas in the middle of
your text and not have it count as a word count or print garbage. Here
is my code:
#include <iostream>
#include <cctype>

using namespace std;

void readAndCount (int &numWords, int letterCount[]);
// Reads a line of input. Counts the words and the number
// of occurrences of each letter.

void outputLetterCounts (int letterCount[]);
// Prints the number of occurrences of each letter that
// appears in the input line.
// =========================
// main function
// =========================
int main()
{
int numWords = 0;
int letterCount[26] = {0}; // stores the frequency of each letter

cout << endl;
cout << "Enter a line of text.." << endl << endl;

readAndCount (numWords, letterCount);

cout << endl;
cout << numWords << " words" << endl;
outputLetterCounts(letterCount);

return 0;
}

// =========================
// Function Definitions
// =========================

void readAndCount (int &numWords, int letterCount[])
{
char c;

do
{
// If the character can't be read for some reason
if ( !cin.get ( c ) )
break;

// Assuming ASCII, and isupper and tolower can't be used
// Convert if upper case letter to lower case
if ( c >= 'A' && c <= 'Z' )
c -= 'A' - 'a';

// Only works with lower case letters
++letterCount[c - 'a'];

if ( c == '\n' || c == '\t' || c == ' '|| c == ',' || c == '.' )
++numWords;
} while ( c != '\n' );
}
void outputLetterCounts(int letterCount[])
{
for (int i = 0; i < 26; i++)
{
if (letterCount[i] > 0)
{
cout << letterCount[i] << " " << char('a' + i) << endl;
}
}
}

Thanks!

Kathy
Oct 17 '05 #1
8 3742
DrNoose wrote:

Hi!

I'm writing a program that is supposed to read a line of input, count
the words and the number of occurrences of each letter. Then it should
prints the number of occurrences of each letter that appears in the
input line. For example, if I typed "I say Hi." it should give the
following output:

3 words
1 a
1 h
2 i
1 s
1 y

Here is my problem. If I type in a phrase like "I ask you, what is
truth? I get this:

7 words
257 a
512 h
257 i
1 k
1 o
256 r
257 s
768 t
257 u
256 w
1 y
Press any key to continue

Why am I getting this bad output? Can anyone see anything in my code
that would cause this.
Which array alement is indexed, when you do
You should be able to put commas in the middle of your text and not have it count as a word count or print garbage. Here
is my code:

#include <iostream>
#include <cctype>

using namespace std;

void readAndCount (int &numWords, int letterCount[]);
// Reads a line of input. Counts the words and the number
// of occurrences of each letter.

void outputLetterCounts (int letterCount[]);
// Prints the number of occurrences of each letter that
// appears in the input line.

// =========================
// main function
// =========================
int main()
{
int numWords = 0;
int letterCount[26] = {0}; // stores the frequency of each letter

cout << endl;
cout << "Enter a line of text.." << endl << endl;

readAndCount (numWords, letterCount);

cout << endl;
cout << numWords << " words" << endl;
outputLetterCounts(letterCount);

return 0;
}

// =========================
// Function Definitions
// =========================

void readAndCount (int &numWords, int letterCount[])
{
char c;

do
{
// If the character can't be read for some reason
if ( !cin.get ( c ) )
break;

// Assuming ASCII, and isupper and tolower can't be used
// Convert if upper case letter to lower case
if ( c >= 'A' && c <= 'Z' )
c -= 'A' - 'a';

// Only works with lower case letters
++letterCount[c - 'a'];

if ( c == '\n' || c == '\t' || c == ' '|| c == ',' || c == '.' )
++numWords;
} while ( c != '\n' );
}

void outputLetterCounts(int letterCount[])
{
for (int i = 0; i < 26; i++)
{
if (letterCount[i] > 0)
{
cout << letterCount[i] << " " << char('a' + i) << endl;
}
}
}

Thanks!

Kathy

--
Karl Heinz Buchegger, GASCAD GmbH
Teichstrasse 2
A-4595 Waldneukirchen
Tel ++43/7258/7545-0 Fax ++43/7258/7545-99
email: kb******@gascad.at Web: www.gascad.com

Fuer sehr grosse Werte von 2 gilt: 2 + 2 = 5
Oct 17 '05 #2
DrNoose wrote:


Why am I getting this bad output? Can anyone see anything in my code
that would cause this. You should be able to put commas in the middle of
your text and not have it count as a word count or print garbage.


Which array element is indexed, when you do:

++letterCount[c - 'a'];

and c has a value of ','?

BTW: DO you have a debugger?
If yes, use it. A debugger is next to your editor the piece
of software in your toolkit you have to use often. A debugger
allows you to eg. single step through your code and examine
variables as they change and as statements are executed.
This gives you a peek at what the program actually *is* doing
in contrast to what you think it *should be* doing.

If you don't have a debugger, then you need to help yourself
by introducing output statements which serve the same purpose:
Give you a look at variables as they change throuh the run of
your program. In your case it would be a good idea to modify
your program eg. like this:

do
{
// If the character can't be read for some reason
if ( !cin.get ( c ) )
break;

cout << "Got next character '" << c << "'" << endl;

// Assuming ASCII, and isupper and tolower can't be used
// Convert if upper case letter to lower case
if ( c >= 'A' && c <= 'Z' )
c -= 'A' - 'a';

cout << "Character used for counting: '" << c << "'" << endl;

int index = c - 'a';

cout << "Index used for the array: " << index << endl;

// Only works with lower case letters
++letterCount[ index ];

if ( c == '\n' || c == '\t' || c == ' '|| c == ',' || c == '.' ) {
cout << "New word detected" << endl;
++numWords;
}

} while ( c != '\n' );

cout << "End of loop" << endl;

When you have those augumentations in place, the program itself will inform
you what it is doing (and in case of the if-s: why it is doing). Usually this
will help you to see where your thinking is flawed.

Modify the program to help you to debug it!
Once the program runs as expected, you can remove all those additional outputs.
And yes: Even professionals work that way, when using a debugger is of no
great help.

--
Karl Heinz Buchegger
kb******@gascad.at
Oct 17 '05 #3
Karl Heinz Buchegger wrote:
DrNoose wrote:

Why am I getting this bad output? Can anyone see anything in my code
that would cause this. You should be able to put commas in the middle of
your text and not have it count as a word count or print garbage.

Which array element is indexed, when you do:

++letterCount[c - 'a'];

and c has a value of ','?

BTW: DO you have a debugger?
If yes, use it. A debugger is next to your editor the piece
of software in your toolkit you have to use often. A debugger
allows you to eg. single step through your code and examine
variables as they change and as statements are executed.
This gives you a peek at what the program actually *is* doing
in contrast to what you think it *should be* doing.

If you don't have a debugger, then you need to help yourself
by introducing output statements which serve the same purpose:
Give you a look at variables as they change throuh the run of
your program. In your case it would be a good idea to modify
your program eg. like this:

do
{
// If the character can't be read for some reason
if ( !cin.get ( c ) )
break;

cout << "Got next character '" << c << "'" << endl;

// Assuming ASCII, and isupper and tolower can't be used
// Convert if upper case letter to lower case
if ( c >= 'A' && c <= 'Z' )
c -= 'A' - 'a';

cout << "Character used for counting: '" << c << "'" << endl;

int index = c - 'a';

cout << "Index used for the array: " << index << endl;

// Only works with lower case letters
++letterCount[ index ];

if ( c == '\n' || c == '\t' || c == ' '|| c == ',' || c == '.' ) {
cout << "New word detected" << endl;
++numWords;
}

} while ( c != '\n' );

cout << "End of loop" << endl;

When you have those augumentations in place, the program itself will inform
you what it is doing (and in case of the if-s: why it is doing). Usually this
will help you to see where your thinking is flawed.

Modify the program to help you to debug it!
Once the program runs as expected, you can remove all those additional outputs.
And yes: Even professionals work that way, when using a debugger is of no
great help.

Karl,

Hi!

I'm a newbie to C++ and I'm am not very good at this programming
thing!!!! LOL.

We have to use Visual Studios to run our programs. I've never used this
software before. Therefore, I don't know all of the things that it can
do, or I should have it be doing other than what the teacher's
instructions say to do!

I'm sure VS has a debugger, I'll just have to look at the program and see.

Thanks for your help!!!

Kathy
Oct 17 '05 #4
"DrNoose" <dr*****@Idontthinkso.com> wrote in message
news:f7******************************@comcast.com. ..
Karl Heinz Buchegger wrote:
DrNoose wrote:
I'm a newbie to C++ and I'm am not very good at this programming thing!!!!
LOL.

We have to use Visual Studios to run our programs. I've never used this
software before. Therefore, I don't know all of the things that it can do,
or I should have it be doing other than what the teacher's instructions
say to do!

I'm sure VS has a debugger, I'll just have to look at the program and see.


Yes, Visual Studio has a very good debugger. But I can indeed
understand that as a novice you might be intimidated by it.
So start by taking Karl's alternate advice: place output statements
at strategic locations in your code. Karl has already show some
good examples of how and where to do this, so I needn't do it again.

Also, when you have time (:-)), I recommend you do become familiar
with your debugger, perhaps with a practice program for which there's
no pressure to get right or complete by a deadline. I promise you'll
be glad you did. :-)

-Mike
Oct 17 '05 #5
Mike Wahler wrote:
"DrNoose" <dr*****@Idontthinkso.com> wrote in message
news:f7******************************@comcast.com. ..
Karl Heinz Buchegger wrote:
DrNoose wrote:


I'm a newbie to C++ and I'm am not very good at this programming thing!!!!
LOL.

We have to use Visual Studios to run our programs. I've never used this
software before. Therefore, I don't know all of the things that it can do,
or I should have it be doing other than what the teacher's instructions
say to do!

I'm sure VS has a debugger, I'll just have to look at the program and see.

Yes, Visual Studio has a very good debugger. But I can indeed
understand that as a novice you might be intimidated by it.
So start by taking Karl's alternate advice: place output statements
at strategic locations in your code. Karl has already show some
good examples of how and where to do this, so I needn't do it again.

Also, when you have time (:-)), I recommend you do become familiar
with your debugger, perhaps with a practice program for which there's
no pressure to get right or complete by a deadline. I promise you'll
be glad you did. :-)

-Mike

Hi!

For some reason my help files didn't get installed. How do I use the
debugger? I have some sample programs I can use if someone will tell me
how it works.

Thanks!

Kathy
Oct 17 '05 #6

"DrNoose" <dr*****@Idontthinkso.com> wrote in message
news:Gq********************@comcast.com...
Mike Wahler wrote:
"DrNoose" <dr*****@Idontthinkso.com> wrote in message
news:f7******************************@comcast.com. ..
Karl Heinz Buchegger wrote:

DrNoose wrote:
I'm a newbie to C++ and I'm am not very good at this programming
thing!!!! LOL.

We have to use Visual Studios to run our programs. I've never used this
software before. Therefore, I don't know all of the things that it can
do, or I should have it be doing other than what the teacher's
instructions say to do!

I'm sure VS has a debugger, I'll just have to look at the program and
see.

Yes, Visual Studio has a very good debugger. But I can indeed
understand that as a novice you might be intimidated by it.
So start by taking Karl's alternate advice: place output statements
at strategic locations in your code. Karl has already show some
good examples of how and where to do this, so I needn't do it again.

Also, when you have time (:-)), I recommend you do become familiar
with your debugger, perhaps with a practice program for which there's
no pressure to get right or complete by a deadline. I promise you'll
be glad you did. :-)

-Mike

Hi!

For some reason my help files didn't get installed.


So install them.
How do I use the debugger?
Read The Directions. Or you could poke around the menus, I'm
sure it's not that hard to find. But the documentation would
be of immense help to get you started.
I have some sample programs I can use if someone will tell me how it
works.


That's what the documentation is for. What you're asking is not
topical for this group.

If you want to ask about this on Usenet, select an appropriate
group or groups. A couple good possibilites are:

microsoft.public.vstudio.general
microsoft.public.vstudio.setup

If your internet provider does not supply these groups, you
can connect directly to Microsoft's news server,
msnews.microsoft.com

In the meantime, if you have a deadline to finish your program
and have difficulty learning your debugger, I recommend you use
the 'output statement' approach that Karl suggested before you
try to tackle the debugger.

-Mike
Oct 17 '05 #7
Hi!

I did the code that Karl said to use. I built it and then told it to
"start" (I'm assuming this is the debug feature). The program compiled
okay and then Debug window I got the following:

'program301.exe': Loaded 'C:\Documents and Settings\drnoose\My
Documents\Visual Studio Projects\program301\Debug\program301.exe',
Symbols loaded.
'program301.exe': Loaded 'C:\WINDOWS\SYSTEM32\ntdll.dll', No symbols loaded.
'program301.exe': Loaded 'C:\WINDOWS\SYSTEM32\kernel32.dll', No symbols
loaded.
The program '[2524] program301.exe: Native' has exited with code 0 (0x0).

I will try reinstalling the help files and see if I can get more
information from them or try to other groups as you suggested.

Thanks!

Kathy

Hi!

For some reason my help files didn't get installed.

So install them.

How do I use the debugger?

Read The Directions. Or you could poke around the menus, I'm
sure it's not that hard to find. But the documentation would
be of immense help to get you started.

I have some sample programs I can use if someone will tell me how it
works.

That's what the documentation is for. What you're asking is not
topical for this group.

If you want to ask about this on Usenet, select an appropriate
group or groups. A couple good possibilites are:

microsoft.public.vstudio.general
microsoft.public.vstudio.setup

If your internet provider does not supply these groups, you
can connect directly to Microsoft's news server,
msnews.microsoft.com

In the meantime, if you have a deadline to finish your program
and have difficulty learning your debugger, I recommend you use
the 'output statement' approach that Karl suggested before you
try to tackle the debugger.

-Mike

Oct 17 '05 #8
"DrNoose" <dr*****@Idontthinkso.com> wrote in message
news:WL********************@comcast.com...
Hi!

I did the code that Karl said to use. I built it and then told it to
"start" (I'm assuming this is the debug feature).
You're trying to use both methods at once. Karl (and I)
are saying to use one or the other. If you've put the
informational outputs in your code, simply run it, don't
use the debugger.
The program compiled okay and then Debug window I got the following:
In the future, please ask about this in a place where it's
topical (such as the groups I suggested), but ...

<OT>

'program301.exe': Loaded 'C:\Documents and Settings\drnoose\My
Documents\Visual Studio Projects\program301\Debug\program301.exe', Symbols
loaded.
This is good. It's what the debugger needs to supply
you with useful information.
'program301.exe': Loaded 'C:\WINDOWS\SYSTEM32\ntdll.dll', No symbols
loaded.
'program301.exe': Loaded 'C:\WINDOWS\SYSTEM32\kernel32.dll', No symbols
loaded.
These don't matter. Ignore them.
The program '[2524] program301.exe: Native' has exited with code 0 (0x0).
This is because what the 'start' button does is to tell the
debugger to run your program up to the first breakpoint
(which would be set by you), or to the end if no breakpoints
are encountered. This last is what happened. Look for a
menu item or button called 'single step', 'step over',
'step' into, or similar.

</OT>

I will try reinstalling the help files and see if I can get more
information from them or try to other groups as you suggested.


OK, good luck.

-Mike
Oct 17 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: regrat | last post by:
It's possible create a javascript which counts all words in a webpage until the point in which I click with the mouse. Any suggests?
4
by: sun6 | last post by:
this is a program counting words from "text_in.txt" file and writing them in "text_out.txt". it uses binary tree search, but there is an error when i use insert () thanks for any help ...
7
by: sathyashrayan | last post by:
Group, Following function will check weather a bit is set in the given variouble x. int bit_count(long x) { int n = 0; /* ** The loop will execute once for each bit of x set,
6
by: gk245 | last post by:
Basically, i want to make a function that will receive a sentence or phrase, and count its words. It would start like this (i think): #include <stdio.h> int count ( char sentence ) {...
3
by: Nhd | last post by:
I have a question which involves reading from cin and counting the number of words read until the end of file(eof). The question is as follows: Words are delimited by white spaces (blanks,...
4
by: bigbagy | last post by:
Notes The programs will be compiled and tested on the machine which runs the Linux operating system. V3.4 of the GNU C/C++ compiler (gcc ,g++) must be used. A significant amount coding is...
3
by: arnuld | last post by:
this is an example programme that counts lines, words and characters. i have noticed one thing that this programme counts space, a newline and a tab as a character. i know: 1. a newline is...
1
by: powerej | last post by:
I have gotten the part of counting how many words are in the string, but the vowels just seem alien to me. Ive tried so many things but never close to a correct answer. I know I need to use...
17
by: Razii | last post by:
This is specifically regarding U++ which is C++ libraries and IDE (please don't whine whether its on or off topic. Right click on the thread and click on ignore instead of wasting time). This is...
2
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and efficiency. While initially associated with cryptocurrencies...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge required to effectively administer and manage Oracle...
1
by: Matthew3360 | last post by:
Hi there. I have been struggling to find out how to use a variable as my location in my header redirect function. Here is my code. header("Location:".$urlback); Is this the right layout the...
0
by: AndyPSV | last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and...
0
by: Arjunsri | last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and credentials and received a successful connection...
1
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web server and have made sure to enable curl. I get a...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important...
0
BLUEPANDA
by: BLUEPANDA | last post by:
At BluePanda Dev, we're passionate about building high-quality software and sharing our knowledge with the community. That's why we've created a SaaS starter kit that's not only easy to use but also...
0
by: Ricardo de Mila | last post by:
Dear people, good afternoon... I have a form in msAccess with lots of controls and a specific routine must be triggered if the mouse_down event happens in any control. Than I need to discover what...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.