Taesian
Taesian

Reputation: 3

Can't read from a text file

#include <iostream>
#include <fstream>
#include <stdio.h>

using namespace std;

int count1 (string fileName){
    ifstream infile;
    infile.open("fileName");
    if (!infile)
     throw "file cannot be opened";
    else{
     string line;
     int characters=0;
     while(getline(infile,line)){
         characters += line.length();
         }
         return characters;
     }
     infile.close();
}

int count2 (string fileName){
     ifstream infile;
     infile.open("fileName");
     if (!infile)
      throw "file cannot be opened";
     else{
      string line;
      int spaces=0;
      while(getline(infile,line)){
         char c;
         if(isspace(c)&&c !='\r')
             spaces++;}
         return spaces;
      }
      infile.close();
}

 int count3 (string fileName){
     ifstream infile;
     infile.open("fileName");
     if (!infile)
      throw "file cannot be opened";
     else{
      string line;
      int lines=0;
      while(getline(infile,line))
       lines++;
      return lines;
      }
      infile.close();
}

 int main(int argc,char** argv)
 {
  try{
      int result1 = count1(argv[1]);
      int result2 = count2(argv[1]);
      int result3 = count3(argv[1]);
      cout<<result1<<' '<<result2<<' '<<result3<<endl;
     } catch (const char *e){
         cout<<e<<endl;
     }
     return 0;
 }

//Trying to fix up my program that is supposed to read from a text file and output the amount of characters, spaces, and lines that it has. I already had a file.txt in the same directory of this program. However, it always say "file cannot be opened". I want to say the problem is dealing with the "fileName", but I'm confused on how I could represent the actual file. *Note: I apologize in advance for my haphazard indentations.

Upvotes: 0

Views: 254

Answers (1)

Ryan Vickers
Ryan Vickers

Reputation: 79

You are trying to open "fileName", i.e. a file called "fileName". I believe what you want is to open the file mentioned when calling the function. Remove the quotes like so:

infile.open(fileName.c_str());

The .c_str() part at the end casts your input string to a c style string so it can be read by the open function.

Now just call the count function with "file.txt"

=== update ===

In response to your comment, I believe I see the problem. You are creating a char c and then testing it without having actually set its value.

Instead of this:

  string line;
  int spaces=0;
  while(getline(infile,line)){
     char c;
     if(isspace(c)&&c !='\r')
         spaces++;}
     return spaces;
  }

Try:

  string line;
  int spaces=0;
  while(getline(infile,line)){
     for (int i = 0; i < line.size(); i++)
         if (line[i] == ' ')
            spaces++;
  }
     return spaces;
  }

P.S. the indentation and braces are kind of driving me crazy :)

Upvotes: 2

Related Questions