[英]C++ Compiler Seemingly Skipping Line of Code
我是C ++編程的新手,很顯然缺少一些東西。 在以下代碼中,編譯器似乎無法識別這一行: lengths[counter] = findDups(crtLine);
我收到一個錯誤:設置了變量“ lengths”但未使用。 當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);
}
這是一個警告,而不是錯誤,它確切地告訴您問題出在哪里:您將東西放到名為lengths
的變量中,但是從不檢查其中的內容,也可能永遠都不會在其中存儲任何內容。
您不會收到類似的names
警告,因為std::string
的賦值運算符具有副作用,並且編譯器假定您對副作用感興趣(而不是稍后再獲取該值)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.