Thread: Letter count

  1. #1
    Unregistered
    Guest

    Letter count

    Hi all,

    I'm supposed to write a program that counts the number of characters, words, and lines in a text file

    ++++++++++++++++++++++++++++++++++++++++++++++

    #include <iostream.h>
    #include <fstream.h>
    #include <stdlib.h>

    int main ()
    {
    ifstream inFile ("file.txt" , ios::in);

    if (!inFile){
    cerr<<"File could not be opened / Does not exist";
    exit (1);
    }

    char character, word[30];
    int letters=0,
    words=0,
    lines = 0;

    while (inFile>>character){
    ++letters;
    if (character == '/n')
    ++lines;
    }

    while (!EOF){
    inFile>>word;
    ++words;
    }
    cout<<"The number of letters in this file -without spaces- are: "<<letters<<endl;
    cout<<"The number of lines is: "<<lines<<endl;
    cout<<"The number of words is : "<<words<<endl;
    return 0;
    }

    ++++++++++++++++++++++++++++++++++++++++++++++

    The program does count the letters correctly, but the number of lines and words stay the same, how come?

  2. #2
    Programming is fun, mkay?
    Join Date
    Oct 2001
    Posts
    490

    Arrow Well for one...

    Well, on this line of your code:


    if (character == '/n')

    I don't know if it matters but I think '/n' should be '\n'
    Website(s): http://www16.brinkster.com/trifaze/

    E-mail: [email protected]

    ---------------------------------
    C++ Environment: MSVC++ 6.0; Dev-C++ 4.0/4.1
    DirectX Version: 9.0b
    DX SDK: DirectX 8.1 SDK

  3. #3
    and when you check the first time for letters or new lines, your file pointer will stay at the end, so he will neverenter your last while loop. I think (not sure)you have to set it back to the beginning of the file. you can do this with fseek. I've never used it, but this is a code sample from the msvc help:
    fseek( stream, 23L, SEEK_SET);

    but this is just a thought, not really sure about this

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. bintree and count (withouth using template)?
    By cubimongoloid in forum C++ Programming
    Replies: 7
    Last Post: 05-24-2009, 06:22 AM
  2. counting letter occurences in a string
    By pjr5043 in forum C++ Programming
    Replies: 35
    Last Post: 05-05-2008, 09:18 PM
  3. Problems with my c letter count program
    By cram55 in forum C Programming
    Replies: 10
    Last Post: 05-30-2007, 04:10 AM
  4. Replies: 1
    Last Post: 03-06-2005, 10:12 AM
  5. Count the number of letter "a" on a sentence
    By imbecile in C in forum C Programming
    Replies: 6
    Last Post: 07-27-2003, 02:32 PM