0

This is my code. I am supposed to count the number of 'duck' in a txt file and print string like "There were 2 ducks in animals01.txt"

Now I get no error and nothing return. Please tell me what's wrong?

#include <iostream> // for printf()
#include <cstdlib> // for exit(), perror()
#include <fstream> // for ifstream

using namespace std;

int main(int argc, char *argv[])
 {
  if (argc!=2) {
  // if argc is not 2, print an error message and exit

  cerr << "Usage: "<< argv[0] << " inputFile" << endl;
  exit(1); // defined in cstdlib

  }
return 0;

int num = 0;
ifstream ifs;

ifs.open(argv[1]);
string line;

do{
    getline(ifs, line);
    cout<<line<<endl;
    if(line == "duck"){num++;}


}while(!ifs.eof());

cout<<"There were"<<num<<"ducks in"<<argv[1]<< endl;

}
王小泉
  • 47
  • 2
  • 6

2 Answers2

0

You have the line return 0; before you actually did anything, and when you return main() the program is terminated.

By the way, don't use while(!ifs.eof()) because the eof flag only gets set at the first attempt to read past the end of the file, not when you read exactly to the end of the file due to a line break at the end. Do something like this. Also, fix your indenting as it is very misleading.

eesiraed
  • 4,626
  • 4
  • 16
  • 34
0

Read the file word by word.

Example:

#include <string>
#include <vector>
#include <fstream>
#include <iostream>
using namespace std;

int main()
{
  string str, strToSearch = "ducks";
  int wordCount = 0;
  ifstream fin("thisfile.txt"); 
  while (fin >> str) // Will read up to eof() and stop at every whitespace it hits. (like spaces!)
  {                  
    if(str==strToSearch)
        wordCount++;
  }
  fin.close(); 
  cout<<"There were"<<wordCount<<"ducks in thisfile.txt"<<endl;
  return 0;
}
Ishpreet
  • 5,230
  • 2
  • 19
  • 35