I have this code but its not working. It comes up with an error when I compile i
ID: 3862099 • Letter: I
Question
I have this code but its not working. It comes up with an error when I compile it regarding this line of code: fstream fin(fileName, ios::in);
The initial reason for the code was to query the user for the name of a file. Open the file, read it, and count and report the number of vowels found in the file. Using C++.
/* C++ Program that counts number of vowels in the file */
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
//Main function
int main()
{
char ch;
string fileName;
int vowelCount=0, aCnt=0, eCnt=0, iCnt=0, oCnt=0, uCnt=0;
//Reading file name
cout << " Input file name: ";
cin >> fileName;
//Opening file in read mode
fstream fin(fileName, ios::in);
//Checking for file existence
if(fin.fail())
{
//Printing error message
cout << " Error!!! Cannot read input file... ";
return -1;
}
//Fetching data from file
while(fin.good())
{
//Reading character from file
fin >> ch;
//Checking for character
switch(ch)
{
//Vowel 'a'
case 'a':
case 'A': aCnt++; vowelCount++; break;
//Vowel 'e'
case 'e':
case 'E': eCnt++; vowelCount++; break;
//Vowel 'i'
case 'i':
case 'I': iCnt++; vowelCount++; break;
//Vowel 'o'
case 'o':
case 'O': oCnt++; vowelCount++; break;
//Vowel 'u'
case 'u':
case 'U': uCnt++; vowelCount++; break;
default: break;
}
}
//Printing final report
cout << " Total number of Vowels: " << vowelCount;
cout << " Vowel 'A': " << aCnt;
cout << " Vowel 'E': " << eCnt;
cout << " Vowel 'I': " << iCnt;
cout << " Vowel 'O': " << oCnt;
cout << " Vowel 'U': " << uCnt;
cout << " ";
return 0;
}
Explanation / Answer
Solution for Problem (C++)
Program :-
#include <iostream>
#include<fstream>
#include<string.h>
using namespace std;
int main( )
{
fstream file;
string fileName;
cout<<"Enter file name ";
cin>>fileName; / /Reading file name
char c;
int nNum=0,aCount=0,eCount=0,iCount=0,oCount=0,uCount=0;
file.open(fileName.c_str());
if (!file)
cout << "NO INPUT FILE!!!" << endl; //Printing error message
while(!file.eof())
{
file.get(c);
if (c == 'a' || c=='A')
{
aCount++;
nNum++;
}
else if(c == 'e' || c=='E')
{
eCount++;
nNum++;
}
else if(c == 'o' || c=='O')
{
oCount++;
nNum++;
}
else if(c == 'i' || c=='I')
{
iCount++;
nNum++;
}
else if(c == 'u' || c=='U')
{
uCount++;
nNum++;
}
}
file.close();
cout << "The Total Number of vowels are "<<nNum<<endl;
cout<<"The count of a is "<<aCount<<endl;
cout<<"The count of e is "<<eCount<<endl;
cout<<"The count of i is "<<iCount<<endl;
cout<<"The count of o is "<<oCount<<endl;
cout<<"The count of u is "<<uCount<<endl;
return 0;
}
Sample file name=example.txt:-
aeious
Sample Output :-
Enter file name example.txt
The Total Number of vowels are 5
The count of a is 1
The count of e is 1
The count of i is 1
The count of o is 1
The count of u is 1
Note :- if last letter in the file is vowel it count 2 times it was only happen for last letter of the file if it is a vowel.
!Thanku