0

我正在开发一个程序,该程序根据用户的输入打印出字数、字符数和行数。但我不断收到这些我完全不知道的错误。我想知道是否有人可以提供帮助。** 我已更改它,但仍然收到错误。抱歉,我是 C++ 新手。

我得到的错误是

 filestat.cpp:47: error: ‘line’ was not declared in this scope
 filestat.cpp: In function ‘int wc(std::string)’:
 filestat.cpp:55: error: ‘line’ was not declared in this scope
 filestat.cpp: In function ‘int cc(std::string)’:
 filestat.cpp:67: error: ‘line’ was not declared in this scope


#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int lc(string fname);
int wc(string fname);
int cc(string fname);

int main(){
string fname,line,command;
ifstream ifs;
int i;
while(true){
    cout<<"---- Enter a file name : ";

    if(getline(cin,line)){
        if(line.length()== 4 && line.compare("exit")== 0){
            cout<<"Exiting";
            exit(0);
        }else{
            string command = line.substr(0,2);
            fname= line.substr(4, line.length() -5);
                if( ifs.fail()){
                    ifs.open(fname.c_str());
                    cerr<< "File not found" <<fname <<endl;
                    ifs.clear();
                }else{
                    if(command.compare("lc")){
                        lc(fname);
                    }else if (command.compare("wc")){
                        wc(fname);
                    }else  if(command.compare("cc")){           
                                      cc(fname);                    
                    }else
                        cout<<"Command unknown. ";


                }
        }
    }
}
return 0;
}

 int lc(string fname){
int count;
while(getline(fname, line)){
    count++;
}
cout<<"Number of lines: "<<count ; 
   }

  int wc(string fname){
int count;
while(getline(fname, line)){
    int pos=line.find_first_of("\n\t ",0);
    while(pos =! string::npos){
        int length=line.length();
        line = line.substr(pos+1, length - pos);
        count++;
    }
  }
cout<< "Number of words: " <<count; 
  }
 int cc(string fname){
int count;
while(getline(fname, line)){
    count = count + line.length();
}

cout<< "Number of words: " <<count;

    }
4

1 回答 1

1

length() 是 std::string 的成员函数。你错过了()

if(line.length== 4 && line.compare("exit")== 0) // line.length()

std::string::length() 也返回一个整数。4不应该被包围""

于 2012-09-13T02:45:36.357 回答