I was working on a program that printed out the word count, character count and line count depending on the user’s input. But I keep getting these error that are completely unknown to me. I was wondering if anyone could help.
** I’ve changed it from previous mistakes and am still receiving errors. Sorry I’m new to C++.
The errors I got were
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;
}
When I set line as a global variable I get the error:
filestat.cpp:48: error: cannot convert ‘std::string’ to ‘char**’ for argument ‘1’ to ‘__ssize_t getline(char**, size_t*, FILE*)’
You have other errors. Firstly, you need to have a local variable
linein each of yourwc,lc, andccfunctions.Secondly, you cannot call
getlineusingfname. It expects anistream. So why don’t you passifsinto your functions?In the above, I also initialised
countand returned it (since you have an int return type and were not returning anything).Similar changes for your other functions.
By the way, you might want to lookup the
string::find_first_offunction and decide whether you really need to replacelinewith a substring every time. Look at the second parameter.