Thread: How many strings in a file?

  1. #1
    Registered User
    Join Date
    Oct 2003
    Posts
    14

    How many strings in a file?

    Is there any way to determine how many separate strings are in a file? I know that using ifstream to open a file for reading, and using that name to output to a string you can output them one by one, but is there a function to count them?
    yo

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    It depends on what you consider to be a string. A text file is one big string, so you can be perfectly correct doing this:
    Code:
    size_t strings_in_file ( ifstream& in )
    {
      return 1;
    }
    Of course, you would be assuming that the file is not empty. If you consider a string a sequence of characters ending with a newline, simply read lines from the file and increment a counter. The same goes with sequences of characters separated by whitespace except you can use the >> operator instead of reading a while line.
    My best code is written with the delete key.

  3. #3
    Registered User eth0's Avatar
    Join Date
    Dec 2003
    Posts
    164
    you will have to read the file in to work with it

    read in the chars to a pointer
    Code:
    while (*ptr != '\0')
        {
            if (*ptr == ' ')
            {
                ++counter;
            }
            ptr++;
        }
        
        cout << "There are " << counter + 1 << " words\n";

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  2. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  3. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 02:53 AM
  4. Batch file programming
    By year2038bug in forum Tech Board
    Replies: 10
    Last Post: 09-05-2005, 03:30 PM
  5. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 04:10 PM