I am assigned a computer science project to execute word counts in the format of
ID: 671688 • Letter: I
Question
I am assigned a computer science project to execute word counts in the format of
The program I have written down so far still comes out to have some error and the # of words and the # of unique words incorrect.
The code:
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include <string>
using std::string;
#include <set>
using std::set;
unsigned long linesc=0;
unsigned long wordc=0;
unsigned long chac=0;
unsigned long unlines=0;
unsigned long unwords=0;
//write this function to help you out with the computation.
void unsigned long countWords(const string& s, set<string>& wl, set<string>& n)
{
string word;
string line;
while(getline(cin,line))
{
linesc++;
chac+=line.size();
wl.insert(line);
for (unsigned int i=0; i <line.size();i++)
{
if (line[i]!= ' ')
{
word+=i;
if( line[i+1]==' '|| line[i+1]==line.size()-1)
{
wordc++;
n.insert(word);
word.clear();
}
}
}
}
unlines = wl.size();
unwords = n.size();
}
int main()
{
cout << linesc << ' ' << wordc << ' ' << chac << ' ' << unlines << ' ' << unwords << endl;
return 0;
}
The error:
g++ -Wall wordcount.cpp -o wordcount
wordcount.cpp:32:79: error: 'signed' or 'unsigned' invalid for 'countWords'
wordcount.cpp: In function 'void countWords(const string&, std::set<std::basic_string<char> >&, std::set<std::basic_string<char> >&)':
wordcount.cpp:49:69: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
make: *** [wordcount] Error 1
[1]+ Done medit "$@" &>/dev/null
Explanation / Answer
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include <string>
using std::string;
#include <set>
using std::set;
unsigned long linesc=0;
unsigned long wordc=0;
unsigned long chac=0;
unsigned long unlines=0;
unsigned long unwords=0;
//write this function to help you out with the computation.
void countWords(const string& s, set<string>& wl, set<string>& n) // modified line. A function cannot be both void and unsigned long returning type.
{
string word;
string line;
while(getline(cin,line))
{
linesc++;
chac+=line.size();
wl.insert(line);
for (unsigned int i=0; i <line.size();i++)
{
if (line[i]!= ' ')
{
word+=i;
if( line[i+1]==' '|| line[i+1]==line.size()-1)
{
wordc++;
n.insert(word);
word.clear();
}
}
}
}
unlines = wl.size();
unwords = n.size();
}
int main()
{
cout << linesc << ' ' << wordc << ' ' << chac << ' ' << unlines << ' ' << unwords << endl;
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.