472,805 Members | 1,584 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

Create program to count words in a file

I have a few documents in which I need to get a total word count.
Can anyone help?
I'd like to create this program so I can get the result after entering
the filename, and
have the option to enter another filename and get results again...
enter quit to end program.

Mar 7 '06 #1
9 18413
This seems to accomplish what I need. Is it clean?

#include <iostream>
// #include <cassert> for Assert Fuction
#include <fstream>
#include <iostream>

using namespace std;

int main()
{

int count;
string fileName;
string astring;
ifstream inFile;

cout << "Enter the name of the file "
<< "(type Quit to end): ";
cin >> fileName;
while (fileName != "Quit")
{
inFile.open(fileName.c_str());

if (!inFile) // How do I use assert function here???
{
cout << "** Can't open the file **" << endl;
return 1;
}

count = 0;

while (inFile >> astring)
count++;

cout << "Number of words in file: " << count << endl;

inFile.close();
inFile.clear();

cout << "Enter the name of the file "
<< "(type Quit to end): ";
cin >> fileName;
}
return 0;
}

Mar 7 '06 #2
"aaron" <aa***@yadavis.com> wrote in message
news:11**********************@i40g2000cwc.googlegr oups.com...
This seems to accomplish what I need. Is it clean?

<snip>

See answer in alt.comp.lang.learn.c-c++

Mar 7 '06 #3
In article <1141723275.549806.324050
@i40g2000cwc.googlegroups.com>, aa***@yadavis.com says...
This seems to accomplish what I need. Is it clean?
Not particularly.
using namespace std;
Most experienced C++ programmers would consider this a
fairly ugly hack -- it's not necessarily terrible, but
certainly not particularly clean either.

[ ... ]
if (!inFile) // How do I use assert function here???


First of all, assert is a macro, not a function (an
important distinction in this case).

Second, assert isn't really suitable for this situation
anyway. It's basically intended to verifying program
logic -- i.e. if its condition is false, it indicates a
problem in your program, rather than data that's supplied
to the program. This is looking at the input data, so an
'if' is a perfectly reasonable way to handle it.

For real use, an interactive program like this that
requires the user to type in file names as it runs is
rarely as useful as a program that accepts file names on
the command line so the user can specify all of them up-
front. Along with that, I'd move the counting into a
separate function:

int count(char const *filename) {
int words = 0;
std::string word;
std::ifstream infile(filename);

if (!infile)
return -1;

while (infile >> word)
++words;

return words;
}

int main(int argc, char **argv) {

for (int i=1; i<argc; i++) {
int words = count(argv[i]);

std::cout << argv[i] << ": ";

if (words < 0)
std::cout << "Unable to open file!\n";
else
std::cout << count(argv[i]) << "\n";
}
return 0;
}

One other possibility would be to use std::distance
instead of an explicit loop to count the words in the
file:

int count(char const *filename) {
std::ifstream infile(filename);

if (!infile)
return -1;

return std::distance(
std::istream_iterator<std::string>(infile),
std::istream_iterator<std::string>());
}

Side note: A typical UNIX shell will expand wildcards and
such, so this will automatically support things like "wc
*.txt". Most shells in Windows don't do that, but most
compilers include code to do it that you can link into
your program if you want it (its name varies from one
compiler to the next though -- e.g. Microsoft calls it
setargv.obj, Borland calls it wildargs.obj, and so on).

--
Later,
Jerry.

The universe is a figment of its own imagination.
Mar 7 '06 #4

Jerry Coffin wrote:
In article <1141723275.549806.324050
@i40g2000cwc.googlegroups.com>, aa***@yadavis.com says...
This seems to accomplish what I need. Is it clean?
Not particularly.
using namespace std;


Most experienced C++ programmers would consider this a
fairly ugly hack -- it's not necessarily terrible, but
certainly not particularly clean either.

[ ... ]


do you mean 'using namespace std;' is an ugly hack?...
if (!inFile) // How do I use assert function here???


First of all, assert is a macro, not a function (an
important distinction in this case).

Second, assert isn't really suitable for this situation
anyway. It's basically intended to verifying program
logic -- i.e. if its condition is false, it indicates a
problem in your program, rather than data that's supplied
to the program. This is looking at the input data, so an
'if' is a perfectly reasonable way to handle it.

For real use, an interactive program like this that
requires the user to type in file names as it runs is
rarely as useful as a program that accepts file names on
the command line so the user can specify all of them up-
front. Along with that, I'd move the counting into a
separate function:

int count(char const *filename) {
int words = 0;
std::string word;
std::ifstream infile(filename);

if (!infile)
return -1;

while (infile >> word)
++words;

return words;
}

int main(int argc, char **argv) {

for (int i=1; i<argc; i++) {
int words = count(argv[i]);

std::cout << argv[i] << ": ";

if (words < 0)
std::cout << "Unable to open file!\n";
else
std::cout << count(argv[i]) << "\n";
}
return 0;
}

One other possibility would be to use std::distance
instead of an explicit loop to count the words in the
file:

int count(char const *filename) {
std::ifstream infile(filename);

if (!infile)
return -1;

return std::distance(
std::istream_iterator<std::string>(infile),
std::istream_iterator<std::string>());
}

Side note: A typical UNIX shell will expand wildcards and
such, so this will automatically support things like "wc
*.txt". Most shells in Windows don't do that, but most
compilers include code to do it that you can link into
your program if you want it (its name varies from one
compiler to the next though -- e.g. Microsoft calls it
setargv.obj, Borland calls it wildargs.obj, and so on).

--
Later,
Jerry.

The universe is a figment of its own imagination.


Mar 7 '06 #5
Fei Liu wrote:
do you mean 'using namespace std;' is an ugly hack?...


The C++ thought leaders formerly said it was, and have since softened their
stance to "mostly harmless".

This repost best describes the issues involved:

Do you remember the scene in Star Trek Old Generation where they could not
get the hatch to a grain silo open, and when Kirk finally opened it
thousands of tribbles rained down all over him?

Kirk represents your source file.

The grain silo represents all the header files your source file includes.

The tribbles each represents an identifier declared inside 'namespace std'
in those headers.

Raining down all over Kirk represents all those identifiers polluting your
local namespace.

'using namespace std' represents sliding the hatch open.

The purpose of the 'namespace' keyword is to prevent this pollution. You
must keep all the tribbles in the grain silo, and only take down the one or
two that you need:

using std::cout;
using std::endl;

Folks use 'using namespace std' in this newsgroup because trivial example
code often uses it; the code is not large enough to have enough of its own
identifiers to potentially conflict with the 'std' ones. But nobody should
use 'using namespace std', and those who post sample code to this newsgroup
should set a good example.

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Mar 7 '06 #6
Fei Liu wrote:
Jerry Coffin wrote:
In article <1141723275.549806.324050
@i40g2000cwc.googlegroups.com>, aa***@yadavis.com says...
This seems to accomplish what I need. Is it clean?


Not particularly.

using namespace std;


Most experienced C++ programmers would consider this a
fairly ugly hack -- it's not necessarily terrible, but
certainly not particularly clean either.

[ ... ]

do you mean 'using namespace std;' is an ugly hack?...

if (!inFile) // How do I use assert function here???

[...and more than 60 lines quoted without merit...]


Please learn to quote only the relevant portions. Thanks.

V
Mar 7 '06 #7
In article <1141771485.909619.196510
@i39g2000cwa.googlegroups.com>, fe*****@gmail.com says...

[ ... ]
Most experienced C++ programmers would consider this a
fairly ugly hack -- it's not necessarily terrible, but
certainly not particularly clean either.

[ ... ]


do you mean 'using namespace std;' is an ugly hack?...


I mean "using namespace std;" is a _fairly_ ugly hack
when it's at file scope. I think without qualifications,
it's overstated, and I think that at other scopes it's
somewhat more acceptable (though still rarely ideal).

--
Later,
Jerry.

The universe is a figment of its own imagination.
Mar 8 '06 #8

Phlip wrote:
Fei Liu wrote:
do you mean 'using namespace std;' is an ugly hack?...


The C++ thought leaders formerly said it was, and have since softened their
stance to "mostly harmless".

This repost best describes the issues involved:

Do you remember the scene in Star Trek Old Generation where they could not
get the hatch to a grain silo open, and when Kirk finally opened it
thousands of tribbles rained down all over him?

Kirk represents your source file.

The grain silo represents all the header files your source file includes.

The tribbles each represents an identifier declared inside 'namespace std'
in those headers.

Raining down all over Kirk represents all those identifiers polluting your
local namespace.

'using namespace std' represents sliding the hatch open.

The purpose of the 'namespace' keyword is to prevent this pollution. You
must keep all the tribbles in the grain silo, and only take down the one or
two that you need:

using std::cout;
using std::endl;

Folks use 'using namespace std' in this newsgroup because trivial example
code often uses it; the code is not large enough to have enough of its own
identifiers to potentially conflict with the 'std' ones. But nobody should
use 'using namespace std', and those who post sample code to this newsgroup
should set a good example.

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!


Thanks for your explanation, Phlip. I understand the reason why
indiscrimnately 'using namespace std' is a bad idea. But it was the
first time I heard it being referred to as 'an ugly hack'. It is
interesting they later relaxed their phrase.

V, as you may or may not be able to see, I wasn't sure what was being
quoted in Phlip's original post as 'an ugly hack' thus my quote of
Phlip's complete message.

Mar 8 '06 #9
thanks Phlip!!!!

Mar 8 '06 #10

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

Similar topics

22
by: Ling Lee | last post by:
Hi all. I'm trying to write a program that: 1) Ask me what file I want to count number of lines in, and then counts the lines and writes the answear out. 2) I made the first part like this: ...
7
by: dog | last post by:
I've seen plenty of articles on this topic but none of them have been able to solve my problem. I am working with an Access 97 database on an NT4.0 machine, which has many Access reports. I...
5
by: name | last post by:
Back for more critique. ---------------------------------------------------------------- #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #define MAX 10000
9
by: santosh | last post by:
Hello all, I've put together a small program to count the number of characters and 'words' in a text file. The minimum length of a word, (in terms of no. of characters), as well as word...
66
by: genestarwing | last post by:
QUESTION: Write a program that opens and read a text file and records how many times each word occurs in the file. Use a binary search tree modified to store both a word and the number of times it...
23
by: sandy | last post by:
I need (okay, I want) to make a dynamic array of my class 'Directory', within my class Directory (Can you already smell disaster?) Each Directory can have subdirectories so I thought to put these...
2
by: pchahar | last post by:
Write a program to process a text file. The program will determine how many unique words there are in the text file that begin with each letter of the alphabet. The text file name will be given as a...
3
by: waynejr25 | last post by:
can anyone help me add a function that will count the occurance of each word in an input file. here's the code i have so far it counts the number of characters, words, and lines but i need the...
5
by: Snaggy | last post by:
Or any other standar unix program.. I want to pass something to a pipe for wc (to count words) and read the result into a variable.. For now I put an intermediate result into a file and then...
0
by: erikbower65 | last post by:
Using CodiumAI's pr-agent is simple and powerful. Follow these steps: 1. Install CodiumAI CLI: Ensure Node.js is installed, then run 'npm install -g codiumai' in the terminal. 2. Connect to...
0
by: erikbower65 | last post by:
Here's a concise step-by-step guide for manually installing IntelliJ IDEA: 1. Download: Visit the official JetBrains website and download the IntelliJ IDEA Community or Ultimate edition based on...
0
by: kcodez | last post by:
As a H5 game development enthusiast, I recently wrote a very interesting little game - Toy Claw ((http://claw.kjeek.com/))。Here I will summarize and share the development experience here, and hope it...
0
by: Taofi | last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same This are my field names ID, Budgeted, Actual, Status and Differences ...
14
DJRhino1175
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
0
by: Rina0 | last post by:
I am looking for a Python code to find the longest common subsequence of two strings. I found this blog post that describes the length of longest common subsequence problem and provides a solution in...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
0
by: lllomh | last post by:
How does React native implement an English player?
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...

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.