i need help with this program: i am counting words and numbers in a text file. T
ID: 667312 • Letter: I
Question
i need help with this program:
i am counting words and numbers in a text file.
The input is one text file, with words and integers, separated by any other symbols including spaces, commas, period,
parentheses and carriage returns. Keep in mind there can be be multiple separators together (e.g. many spaces, many
commas together).
the cpp line below is my own work, i can get number of numbers right but number of words wrong.
for example: input1.txt has 6 words but my word count is 5
#include <iostream>
#include <fstream>
#include <cstring>
#include <string>
using namespace std;
int main ()
{
// enter file name
string filename;
cout << "enter a file name: ";
cin >> filename;
// open file
ifstream fin (filename.c_str());
// notify a failed open
if(fin.fail())
{
cout << "file cannot be opened" << endl;
}
char ch; // track character stream in
char word[30]; // track a word
char num[10]; // track a sequence of numbers
int count1 = 0; int count2 = 0; // count1 is word count, count2 is number count
int w = 0; // index for word
int n = 0; // index for number
//get 1st character
fin.get(ch);
// get the rest character
while (!fin.eof())
{
cout << ch;
//if the character is alpha, index +1 and get another character
if (isalpha(ch))
{
word[w] = ch;
w++;
fin.get(ch);
}
// if the character is digit, index +1 and get another character
else if (isdigit(ch))
{
num[n] = ch;
n++;
fin.get(ch);
}
// if character is neither alpha nor digit, if the word index > 0 or number index >0 then word count or number count +1, reset w and n
// get another character
else
{
if(w>0) count1++;
else if (n>0) count2++;
w=0;
n=0;
fin.get(ch);
}
}
//output result
cout << endl;
cout << "words=" << count1 << " numbers=" << count2 << endl;
// close file
fin.close();
return 0;
}
input1.txt:
The cat is [there]
10 20 3.1416,,1000
another cat
Explanation / Answer
#include<fstream>
#include<iostream>
#include<string>
using namespace std;
int main()
{
ifstream inFile; //Declares a file stream object
string fileName;
string word;
int count = 0;
cout << "Please enter the file name ";
getline(cin,fileName);
inFile.open(fileName.c_str());
while(!inFile.eof())
{
inFile >> word;
count++;
}
cout << "Number of words in file is " << count;
inFile.close();
cin.get();
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.