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

时间:2012-06-11 23:40:22

标签: 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);

}

1 个答案:

答案 0 :(得分:6)

这是一个警告,而不是错误,它会告诉您问题的确切原因:您将事物放入名为lengths的变量中,但从不检查其中的内容,您可能会并且从不在第一时间存储任何东西。

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