-
January 29th, 2012, 05:10 PM
#1
Need to print out number of words and lines in a file
My instructor kind of assumed we'd know how to do this. I kind of get the idea, but I don't know what to do with the cstring I generate when I tokenize it.
He said to:
Write a program that prompts the user for the name of a file. Then it opens the file, and counts the number of words and lines in the file, and prints out those counts.
I think I possibly could somehow use a counter to increment using getLIne() until getLine() returns NULL, but the problem is, I'm worried if I try that, a file that looks like this:
Bla bla bla bla bla lkfdljkfaklafdskjladsjkdfkjlkdfjdfshafdsjkjrerjkkjfaddjkfsafkjdjakdfsjkasfjkjkfdskjldfjkfjkdjfkdsakdjfkjfdkjdfskjfdskjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjdfkerea
blkjadkjlfdskjldfkjlfdkjfdjkdfsjkldfskljfksfdljfd
Only register four lines and not get the one after the fourth line.
So I was thinking of something like
Code:
#include <iostream>
#include<ifstream>
#include<cstring>
#include<string>
#include<vector>
#include <cstdlib>
using namespace std;
iostream keyboard;
ifstream file;
iostream cin;
iostream cout;
vector<int> v;
int main()
{
int lineCount = 0;
string filename;
cout << "Enter a file name.";
cin >> filename;
file(filename);
char* ch;
int tempWord = 0;
ch = strtok(line, "%s\");
while (ch != NULL)
{
tempWord++;
}
v.push_back(tempWord);
lineCount++;
while(!file.eof())
{
string line = file.nextLine();
char* ch;
int tempWord = 0;
ch = strtok(line, "%s\");
while (ch !=NULL)
{
tempWord++;
}
v.push_back(tempWord);
lineCount++;
}
cout <<"Line count: " << lineCount;
int total;
for (int i =0; i < v.size(); i++)
{
total = total + v[i];
}
cout << "Word count: " << total;
return 0;
}
Did I do that right?
Will that count the number of words and number of lines correctly?
I really need help now. It's due tomorrow.
Last edited by jedipenguin; January 29th, 2012 at 05:45 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|