473,661 Members | 2,440 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 outputLetterCou nts (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;
outputLetterCou nts(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 outputLetterCou nts(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 3850
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 outputLetterCou nts (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;
outputLetterCou nts(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 outputLetterCou nts(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*****@Idontt hinkso.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*****@Idontt hinkso.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*****@Idontt hinkso.com> wrote in message
news:Gq******** ************@co mcast.com...
Mike Wahler wrote:
"DrNoose" <dr*****@Idontt hinkso.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
instructio ns 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.publi c.vstudio.gener al
microsoft.publi c.vstudio.setup

If your internet provider does not supply these groups, you
can connect directly to Microsoft's news server,
msnews.microsof t.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\drnoos e\My
Documents\Visua l Studio Projects\progra m301\Debug\prog ram301.exe',
Symbols loaded.
'program301.exe ': Loaded 'C:\WINDOWS\SYS TEM32\ntdll.dll ', No symbols loaded.
'program301.exe ': Loaded 'C:\WINDOWS\SYS TEM32\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.publi c.vstudio.gener al
microsoft.publi c.vstudio.setup

If your internet provider does not supply these groups, you
can connect directly to Microsoft's news server,
msnews.microsof t.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*****@Idontt hinkso.com> wrote in message
news:WL******** ************@co mcast.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\drnoos e\My
Documents\Visua l Studio Projects\progra m301\Debug\prog ram301.exe', Symbols
loaded.
This is good. It's what the debugger needs to supply
you with useful information.
'program301.exe ': Loaded 'C:\WINDOWS\SYS TEM32\ntdll.dll ', No symbols
loaded.
'program301.exe ': Loaded 'C:\WINDOWS\SYS TEM32\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
2126
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
4068
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 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h>
7
4800
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
1859
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 ) { char string ;
3
6346
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, tabs, linefeeds, returns). It will print 3 pieces of information before exit: the first word, the last word, and the number of words read, with one blank in between fields. Input lines of words Output
4
8433
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 needed for this assignment. 1.Counting Words in C++ Problem: Write an elegant C++ program to count the number of times each word occurs in a file. A word is defined as a sequence of characters surrounded by whitespace. Case is not important, so...
3
1867
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 represented as '\n' 2. a tab as '\t' 3. a space as ' '
1
2423
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 charAt() and length() some nested loops with do while and for, but cant seem to get headed in the right direction. Also when i click the cancel button my program is suppose to end and tell you how many lines were entered, a count of vowels from all lines...
17
1618
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 specifically for Mirek Fidler. I am on a new computer (with Vista instead of XP, 3 gig ram, and 3 core phenom). I downloaded U++ IDE (with mingw). Compiled the counting words benchmark (with MINGW speed option) and it was much slower than before...
0
8432
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8343
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8855
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8545
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8633
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6185
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4179
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4346
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2762
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.