Search code examples
c++logicprogramming-languages

How to fix not printing any character and just count vowels and characters and read every character in a file


I just want to read every character in a file where I put characters from A TO Z but the program prints A every time and count vowels 4 and character 25 but expectation was to printing vowels 5 and characters 26 how to fix this program fixing from last 4 hours but nothing progress? Code:

#include<iostream>
#include<fstream>
#include<string>

using namespace std;

int main() {
  int i, count = 0, vowel_count = 0;
  string file_name;
  cout << "enter file name:";
  cin >> file_name;
  ifstream fin;
  fin.open(file_name);
  char ch;
  while (!fin.eof()) {
    fin.get(ch);
    cout << ch;
    while (fin >> ch) {
      i = ch;
      if ((i > 63 && i < 91) || (i > 96 && i < 123))
        count++;
      if (i == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')
        vowel_count++;
    }
    cout << "\n No. of Characters in a File : " << count;
    cout << "\n No. of vowel characters in the File  : " << vowel_count;
  }
  fin.close();
  return 0;
}

Solution

  • You have some really minor erros in the code, which I fixed for you.

    Additionally, I added a check, if the file could be opened or not. That is the problem in most cases.

    Please see below:

    #include<iostream>
    #include<fstream>
    #include<string>
    
    using namespace std;
    
    int main() {
        int count = 0, vowel_count = 0;
        string file_name;
        cout << "\nEnter file name: ";
        cin >> file_name;
        ifstream fin(file_name);
        if (fin) {
            char ch;
            while (fin.get(ch)) {
                cout << ch;
                if ((ch >= 'A' && ch <= 'Z') || (ch > 'a' && ch <= 'z'))
                    count++;
                if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')
                    vowel_count++;
    
            }
            fin.close();
    
            cout << "\n No. of Characters in a File : " << count;
            cout << "\n No. of vowel characters in the File  : " << vowel_count;
        }
        else std::cerr << "\n\n*** Error. Could notopen '" << file_name << "'\n\n";
        return 0;
    }