2012-09-13 63 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不應包含在""中。