Hello all. This function is supposed to look at a file (which is opened in the main routine) and print the smallest word in the file. However, I keep getting "Error: Expression must have a class type" under printfile after the if statement.
1 2 3 4 5 6 7 8 9 10 11
int smallestword(ifstream &infile, string &printfile)
{
string smalls;
while (getline(infile, printfile)) {
for (int i = 0; i < printfile.length; i++) {
if (printfile[i].length > smalls.length())
smalls = printfile[i];
}
}
cout << smalls << endl;
}
I'm still learning and trying to understand these errors. Any help is appreciated.
The length() function applies to the whole string not just 1 char inside it. It also returns a std::size_t type which is the largest unsigned type the system has, where as the int is signed, hence the mismatch warning. So:
1 2 3
for (std::size_t i = 0; i < printfile.length(); i++) {
}
In future please post the compiler output verbatim, we would rather see the whole actual message rather than one's interpretation of, or part of it :+) Make sure the line numbers referred to match up with the line numbers in the code posted. The code tags have a firstline option so that you can have the correct line numbers.
Ideally post a small complete program that reproduces the problem, then we can compile it right here with cpp.sh , possibly setting the warnings levels higher than what you may have :+)