我正在編寫一個程序,它根據用戶的輸入輸出字數,字符數和行數。但是我不斷收到這些完全不爲我所知的錯誤。我想知道有沒有人可以幫忙。 **我從之前的錯誤中改變了它,並且仍然收到錯誤。對不起,我是C++新手。在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;
}
當我設置線作爲一個全局變量我得到的錯誤:
filestat.cpp:48: error: cannot convert ‘std::string’ to ‘char**’ for argument ‘1’ to ‘__ssize_t getline(char**, size_t*, FILE*)’
你可以使代碼更大量使用縮進正確讀取。 (也許你是混合空格字符與製表符。從來不是一個好主意。) – jogojapan