-1

Hello all I have to make a program that counts all the characters that are in a given text file I have no errors when I compile it. But when I run it it prompts and takes the name of my file but then ends. Here is my code.

#include <string>
#include <iostream>
#include"counterType.h"
#include <fstream>
#define MAX 1000
using namespace std;
void countchar(counterType intchar, ifstream& indata);
int main()
{
    ifstream indata;
    counterType intchar;
    cout << "What file would you like to read?" << endl;
    string filename = "empty"; 
    cin >> filename;
    indata.open(filename);
    return 0;
    countchar(intchar, indata);
    intchar.displayCounter();
}

void countchar(counterType intchar, ifstream& indata)
{   
    string x;
    indata >> x;
    while(!indata.eof()) {
        indata >> x;
        intchar.incrementCounter(); 
    }
}   
Asteroids With Wings
  • 16,164
  • 2
  • 17
  • 33
  • 4
    Remove `return 0;` – Richard Critten Jan 28 '21 at 19:29
  • What is `counterType`? What is `countchar`? What is `incrementCounter()`? Are you aware that a `string` is _not_ the same as a character? That don't involve reading all of it? Why do you `return` halfway through your program? Why don't you just use one of the traditional methods for determining the size of a file? – Asteroids With Wings Jan 28 '21 at 19:29
  • You are passing a copy of `counterType` to `counterchar()` so any changes (counts) made are not reflected upon return – doug Jan 28 '21 at 19:29
  • 1
    Also note that your usage of `while(!indata.eof())` is [wrong](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons). – MikeCAT Jan 28 '21 at 19:30
  • 3
    Increase the warning level on your compiler. Some compilers can help you to spot things like this. `g++` and `clang++` have `-Wall -Wextra` that catches a lot. – Ted Lyngmo Jan 28 '21 at 19:30
  • 1
    Unrelated: If you put the function `countchar` above `main` you don't need that prototype above `main` that you have now. – Ted Lyngmo Jan 28 '21 at 19:34

1 Answers1

1

The line

    return 0;

makes it return from the function and prevents executing lines after that. You should remove that to execute countchar(intchar, indata); and intchar.displayCounter();.

MikeCAT
  • 61,086
  • 10
  • 41
  • 58