I am new to C++ programming and am obviously missing something. In the following code the compiler doesn’t seem to recognize this line: lengths[counter] = findDups(crtLine); I get an error: variable “lengths” set but not used. I cannot figure out why it is not recognizing this line, when the names[counter] = getNameOnly(crtLine) works perfectly and it is essentially the same format. Any insight into this issue is appreciated!
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
string getNameOnly (string line) {
return line.substr(0, line.find(' '));
}
int findDups (string line) {
string lnCpy = line;
sort(lnCpy.begin(), lnCpy.end());
int i = 0;
int dups = 0;
int j = 1;
int len = lnCpy.length();
while (j < len) {
if (lnCpy.at(i) == lnCpy.at(j))
dups++;
i++;
j++;
}
if (dups != 0)
return 0;
else
return lnCpy.length();
}
int main() {
string names[1219];
int lengths[1219];
string crtLine;
int counter = 0;
ifstream myfile ("dist.male.first");
if (myfile.is_open()) {
while (!myfile.eof()) {
getline(myfile,crtLine);
lengths[counter] = findDups(crtLine);
names[counter] = getNameOnly(crtLine);
counter++;
}
myfile.close();
}
else cout << "Unable to open file";
return (0);
}
That’s a warning, not an error, and it tells you exactly what the problem is: you put things into the variable named
lengths, but never check what’s in it, you might as well never store anything there in the first place.You don’t get a similar warning for
names, because the assignment operator ofstd::stringhas side effects, and the compiler assumes you were interested in the side effect (rather than getting the value out later).