Nezzie
Nezzie

Reputation: 13

Reading a .dat file and cout'ing?

I have a HW assignment and I have to basically read a .dat file and do the following:

  1. Count the number of characters in the file.
  2. Count the number of words in the file.
  3. Count the number of sentences in the file.
  4. Count the number of lines in the file.
  5. Find the line with the most characters.

I believe that I have the correct code to do this already(No errors when compiled). The problem is that when I compile and run, Visual Studio opens and immediately closes the window. It is not printing out the part where I tell it to cout. I don't know if it's not reading the .dat file or if I put the cout in the wrong spot! I don't have to print out whats in the .dat file. I just have to print out the 5 steps above. Can some help me figure this out?

#include "stdafx.h"
#include <fstream>
#include <iostream>
using namespace std;

void main()
{
ifstream input ("LAB4.DAT");

long c;
long characters = 0;
long words = 0;
long counter = 0;
long sentences =0;
long newlines = 0;
long havealpha;

while ((c=input.get()) != EOF)
{

    ++characters;
    if(isalpha(c))
        havealpha=true;
    if (isspace(c) && havealpha)
    {
        ++words;
        havealpha=false;
    }

    if (c=='.')
        counter = 2;
    if (c==' ')
        --counter;
    if (c=='\n')
        counter = 0;
    if (counter <= 0)
    {
        ++sentences;
        counter = 0;
    }

    if (c=='\n') 
        ++newlines;

    long total = 0;
    long line = 0;
    long totaltemp = 0;
    long linetemp = 0;
    while (c!='\n')
    {
        ++total;
        ++line;
        if (total > totaltemp)
        {
            totaltemp = total;
            linetemp = line;
        }
        if (c=='\n')
        {
            total = 0;
            line = 0;
        }
    }
        cout<<characters<<"Characters"<<words<<"Words"<<sentences<<"Sentences"                        <<newlines<<"New Lines"<<"The longest line is"<<linetemp<<"with"<<totaltemp<<"characters"   <<endl;

}




}

Upvotes: 1

Views: 769

Answers (1)

Beowulf
Beowulf

Reputation: 420

1.For the case of windows just closing, Start the project with Ctrl+F5 instead of just F5. read: How to keep the console window open in Visual C++?

Further, you can avoid that by using a cin.get(); before you exit from main.

  1. Secondly, while (c!='\n') will go into an infinite loop because the value of c never changes inside the block. for all your logic to fall into a place, while(c!='\n') should be just below while ((c=input.get()) != EOF){. So that you can focus on one line at a time.

  2. Keep the characters variable for counting overall character length, make a new variable to count character in that particular line.

Rest is just cleaning up.

Upvotes: 1

Related Questions