C++编译器看似跳过代码行

K G*_*ble 1 c++

我是C++编程的新手,显然缺少一些东西.在下面的代码中,编译器似乎没有识别出这一行:lengths[counter] = findDups(crtLine);我收到一个错误:变量"length"已设置但未使用.我无法弄清楚为什么它不能识别这条线,当names[counter] = getNameOnly(crtLine)它完美地工作并且它基本上是相同的格式.任何洞察这个问题的人都表示赞赏!

#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);
Run Code Online (Sandbox Code Playgroud)

}

Ben*_*igt 6

这是一个警告,而不是一个错误,它告诉你究竟是什么问题:你把东西放入名为变量的变量中lengths,但是从不检查它中的内容,你可能也从不在那里存储任何东西.

你没有得到类似的警告names,因为赋值运算符std::string有副作用,编译器假定你对副作用感兴趣(而不是后来得到值).