无法从文本文件中读取

时间:2015-09-13 16:20:24

标签: c++ counting

#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;
 }

//尝试修复我应该从文本文件中读取的程序,并输出它具有的字符,空格和行数。我已经在这个程序的同一目录中有一个file.txt。但是,它总是说&#34;文件无法打开&#34;。我想说问题是处理&#34; fileName&#34;,但我对如何表示实际文件感到困惑。 *注意:我提前为我随意的缩进道歉。

0 个答案:

没有答案