Need to print out number of words and lines in a file - Page 2
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 2 of 2 FirstFirst 12
Results 16 to 23 of 23

Thread: Need to print out number of words and lines in a file

  1. #16
    Join Date
    Aug 2009
    Posts
    439

    Re: Need to print out number of words and lines in a file

    Basically you need your program to do two things, count the number of lines and count the number of words in a file. Luckily there is a getline function available. Also, there is a version that takes a filestream and a string. Something like this:
    Code:
    std::string aLine;
    std::ifstream myFile( filename.c_str() );
    
    // To get one line from the file
    getline( myFile, aLine )
    In the above snippet, aLine will now contain the first line of the file. Now, you need to figure out how many words are in that line. You can use strtok, but I am quite fond of stringstreams. With them I can do something like:

    Code:
    std::stringstream tempStream( aLine );
    std::string temp;
    while( tempStream >> temp )
    {
        // Do something
    }
    A stringstream provides a nice interface from converting from a string to a stream and back to a string again. What I did above was convert the line into a stream. This lets me have control over parsing, counting, etc.

    As Paul has mentioned, learning to use the debugger is vital. Also, Google is your friend. Be sure to examine the examples. Try not to panic. You will save yourself time by spending a little extra up front examining the examples and understanding them. Afterward, if you have a question about an example, then by all means, you can ask.

    Finally, with the two things I mentioned here (and, pretty much using just the two things), I would be able to write a program to do your assignment.

    I hope this helps you.

  2. #17

    Re: Need to print out number of words and lines in a file

    I've tried that and now I'm getting a segmentation fault. (Right now I'm telling it to use the filename as a command line argument rather than read in to see if it just can't read files.

    Code:
    #include<fstream>
    #include<istream>
    #include<string>
    #include<vector>
    #include<iostream>
    #include<stdio.h>
    #include<ios>
    #include "string.h"
    #include<sstream>
    
    using namespace std;
    
    ifstream keyboard;
    fstream file;
    
    vector<int> v;
    int main(int argc,char *argv[])
    {
    
    char* str;
    
    
    int lineCount = 0;
    char* filename;
    cout << "Enter a file name. \n";
    cin >> filename;
    
    
    //file.open(filename);
    file.open(argv[1]);
    
     if (!file.is_open())
      {
        cout <<"Could not open file"<<endl;
        return -1;
      }
    cout << "Went here.";
    string line;
    std::string temp;
     getline(file,line);
     std::stringstream tempStream(line);
    char* ch;
    int tempWord = 0;
    
    
    	// ch = strtok(line, " ");
    
    while (tempStream >> temp)
    {
    tempWord++;
    }
    
    v.push_back(tempWord);
    lineCount++;
    cout << "Went here.";
    while(!file.eof())
    {
    
    getline(file,line);
     std::stringstream tempStream(line);
     std::string temp;
    char* ch;
    int tempWord = 0;
    	// ch = strtok(line, " ");
    
    while (tempStream >> temp)
    {
    tempWord++;
    
    }
    
    v.push_back(tempWord);
    lineCount++;
    
    
    
    
    
    }
    file.close();
    cout <<"Line count: " << lineCount;
    
    int total;
    for (int i =0; i < v.size(); i++)
    {
    total = total + v[i];
    }
    
    cout << "Word count: " << total;
    
    return 0;
    }
    It's getting as far as the line that asks for the file name and after that is read in, it says "Segmentation fault." and ends abnormally.

    I'm assuming it's probably something wrong with my vector, but what am I doing wrong?

    Also, should the filename be of type

    char*
    or of type
    string?
    Last edited by jedipenguin; January 30th, 2012 at 01:02 PM.

  3. #18
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,197

    Re: Need to print out number of words and lines in a file


  4. #19

    Re: Need to print out number of words and lines in a file

    Ok, I removed the file in and now it works somewhat. However, why is my word count like - 1 billion?

    Also, why would my file read thing cause a segmentation fault?

    Code:
    #include<fstream>
    #include<istream>
    #include<string>
    #include<vector>
    #include<iostream>
    #include<stdio.h>
    #include<ios>
    #include "string.h"
    #include<sstream>
    
    using namespace std;
    
    ifstream keyboard;
    fstream file;
    
    vector<int> v;
    int main(int argc,char *argv[])
    {
    
    char* str;
    
    
    int lineCount = 0;
    //char* filename;
    cout << "Enter a file name. \n";
    //cin >> filename;
    
    if (argc!=2)
      { 
        cout <<"Please enter file name."<<"\n";
        return -1;
      }
    //file.open(filename);
    file.open(argv[1]);
    
     if (!file.is_open())
      {
        cout <<"Could not open file"<<"\n";
        return -1;
      }
      
      
    
    string line;
    std::string temp;
     getline(file,line);
     std::stringstream tempStream(line);
    char* ch;
    int tempWord = 0;
    
    
    	// ch = strtok(line, " ");
    
    while (tempStream >> temp)
    {
    tempWord++;
    }
    
    v.push_back(tempWord);
    lineCount++;
    
    while(!file.eof())
    {
    
    getline(file,line);
     std::stringstream tempStream(line);
     std::string temp;
    char* ch;
    int tempWord = 0;
    	// ch = strtok(line, " ");
    
    while (tempStream >> temp)
    {
    tempWord++;
    
    }
    
    v.push_back(tempWord);
    lineCount++;
    
    
    
    
    
    }
    file.close();
    cout <<"Line count: " << lineCount;
    cout <<"\n";
    
    int total;
    for (int i =0; i < v.size(); i++)
    {
    total = total + v[i];
    }
    
    cout << "Word count: " << total;
    cout <<"\n";
    return 0;
    }
    Also, there are 6 lines, not 7. How do I fix that?

    Line count: 7
    Word count: -1218673904

  5. #20

    Re: Need to print out number of words and lines in a file

    Quote Originally Posted by GCDEF View Post
    I'm unsure of whether I should be using the fstream getline or the global getline.

  6. #21
    Join Date
    Apr 1999
    Posts
    27,444

    Re: Need to print out number of words and lines in a file

    Quote Originally Posted by jedipenguin View Post
    Ok, I removed the file in and now it works somewhat. However, why is my word count like - 1 billion?
    Please debug your code. If you did that, the error is obvious:
    Code:
        int total;
        for (int i =0; i < v.size(); i++)
        {
            total = total + v[i];
        }
    What is the value of "total" before the loop is executed? Didn't you see that when you debugged your code? (you're responsible for debugging your own code).

    Also, please use proper indentation.
    Code:
    #include<fstream>
    #include<istream>
    #include<string>
    #include<vector>
    #include<iostream>
    #include<stdio.h>
    #include<ios>
    #include "string.h"
    #include<sstream>
    
    using namespace std;
    
    ifstream keyboard;
    fstream file;
    
    vector<int> v;
    int main(int argc,char *argv[])
    {
    
        char* str;
    
    
        int lineCount = 0;
        cout << "Enter a file name. \n";
    
        if (argc!=2)
        {
            cout <<"Please enter file name."<<"\n";
            return -1;
        }
        file.open(argv[1]);
    
        if (!file.is_open())
        {
            cout <<"Could not open file"<<"\n";
            return -1;
        }
    
        string line;
        std::string temp;
        getline(file,line);
        std::stringstream tempStream(line);
        char* ch;
        int tempWord = 0;
    
        while (tempStream >> temp)
        {
            tempWord++;
        }
    
        v.push_back(tempWord);
        lineCount++;
    
        while (!file.eof())
        {
    
            getline(file,line);
            std::stringstream tempStream(line);
            std::string temp;
            char* ch;
            int tempWord = 0;
            while (tempStream >> temp)
            {
                tempWord++;
    
            }
            v.push_back(tempWord);
            lineCount++;
    
        }
        file.close();
        cout <<"Line count: " << lineCount;
        cout <<"\n";
    
        int total;
        for (int i =0; i < v.size(); i++)
        {
            total = total + v[i];
        }
    
        cout << "Word count: " << total;
        cout <<"\n";
        return 0;
    }
    Regards,

    Paul McKenzie

  7. #22

    Re: Need to print out number of words and lines in a file

    I thought that, like in Java, primitives automatically initialize.

    Also, I fixed that and my line count is still 1 too high and I'm still getting a segmentation fault.


    Can't indent. Machine doesn't have a C++ compiler other than through the server Exceed on Demand, which I can't figure out how to get it to auto indent.

    Netbeams can't recognize a C++ compiler and anyway, I told it to format but the code below was how it formatted it.
    Code:
    
    
    #include<fstream>
    #include<istream>
    #include<string>
    #include<vector>
    #include<iostream>
    #include<stdio.h>
    #include<ios>
    #include "string.h"
    #include<sstream>
    
    using namespace std;
    
    ifstream keyboard;
    
    
    vector<int> v;
    
    int main() {
    
        char* str;
    
    
        int lineCount = 0;
        char* filename;
        cout << "Enter a file name. \n";
        cin >> filename;
    
    
        //file.open(filename.c_str());
        fstream file(filename, fstream::in | fstream::out);
    
        //file.open("file.txt");
        //file.open(argv[1]);
    
    
    
    
    
        string line;
        std::string temp;
        getline(file, line);
        std::stringstream tempStream(line);
        char* ch;
        int tempWord = 0;
    
    
        // ch = strtok(line, " ");
    
        while (tempStream >> temp) {
            tempWord++;
        }
    
        v.push_back(tempWord);
        lineCount++;
    
        while (!file.eof()) {
    
            getline(file, line);
            std::stringstream tempStream(line);
            std::string temp;
            char* ch;
            int tempWord = 0;
            // ch = strtok(line, " ");
    
            while (tempStream >> temp) {
                tempWord++;
    
            }
    
            v.push_back(tempWord);
            lineCount++;
    
    
    
    
    
        }
        file.close();
        cout << "Line count: " << lineCount;
        cout << "\n";
    
        int total = 0;
        for (int i = 0; i < v.size(); i++) {
            total = total + v[i];
        }
    
        cout << "Word count: " << total;
        cout << "\n";
        return 0;
    }
    Last edited by jedipenguin; January 30th, 2012 at 01:57 PM.

  8. #23
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Fairfax, VA
    Posts
    10,891

    Re: Need to print out number of words and lines in a file

    Quote Originally Posted by jedipenguin View Post
    I'm unsure of whether I should be using the fstream getline or the global getline.
    The fstream's getline (which is actually inherited from istream) takes a C-style string (char array) as its input destination. This brings along with it all the perils of C-style strings, so I do not recommend it.

    The global getline is for use with std::strings, which are much safer and easier to use.

Page 2 of 2 FirstFirst 12

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center