2012-09-13 52 views
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; 

    } 
+2

'fname,c_str()'不太对。另外,你的第一个'else'大概是缺少一个大括号。 – chris

+0

你的花括号不匹配 – aland

回答

1

长度()是性病的成员函数: :string。你错过了()

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

另外std :: string :: length()返回一个整数。 4不应包含在""中。