Thread: Get the number of letters stored in a text file

  1. #1
    Registered User
    Join Date
    Dec 2021
    Posts
    5

    Get the number of letters stored in a text file

    I have a text file with an unknown number of letters and I want to find the number of letters in it using fstream, how should I do it?
    I cant use getline and then find the number by counting, as I don't know the length of the array I should initialize.
    Plz Help
    Thanks!

  2. #2
    Registered User
    Join Date
    Sep 2020
    Posts
    150
    You don't need to store the text. You can read the file char by char and check if if is a letter.
    Code:
    #include <iostream>
    #include <fstream>
    
    
    int main()
    {
        if(std::ifstream input{__FILE__})
        {
            char ch;
            int letterCount = 0;
            
            while(input.get(ch))
            {
                // if ch is letter increment letterCount;
            }
            // output letterCount
        }
        else
            std::cerr << "Error opening file\n";        
    }
    BTW:
    C++ is not C where you need to allocate arrays or strings. std::string and std::vector will do this for you.
    Last edited by thmm; 02-16-2022 at 01:50 AM. Reason: Fixed formatting

  3. #3
    Registered User
    Join Date
    Dec 2021
    Posts
    5
    Thaaaaaankssss!!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Version number stored in .exe!
    By Marreoragarn in forum C Programming
    Replies: 6
    Last Post: 02-24-2015, 11:25 AM
  2. Replies: 2
    Last Post: 09-11-2013, 11:12 PM
  3. Replies: 3
    Last Post: 11-14-2012, 07:13 AM
  4. Replies: 6
    Last Post: 03-07-2011, 02:15 PM
  5. Count number of letters and numbers in a file
    By jtullo in forum C Programming
    Replies: 2
    Last Post: 04-21-2008, 01:33 AM

Tags for this Thread