我正在嘗試使用動態編程來查找哪些項目要在一定的權重容量下從文本文件中選擇,同時使值最大化。該文件的格式如下:從文件中讀取C++ Ifstream
item1, weight, value
item2, weight, value
可變數量的項目。我在讀取主要方法中的文件時遇到問題,我試圖錯誤地檢查錯誤的輸入。我的問題來自於我檢查重量是否丟失,或者是字符串而不是int。我無法弄清楚如何單獨檢查一個字符串,或者如果在那個地方沒有任何東西。我應該輸出一個不同的錯誤,這取決於它是哪一個。謝謝。
int main(int argc, char * const argv[])
{
std::vector<Item> items;
if (argc != 3)
{
std::cerr << "Usage: ./knapsack <capacity> <filename>";
return -1;
}
int capacity;
std::stringstream iss(argv[1]);
if (!(iss >> capacity) || (capacity < 0))
{
std::cerr << "Error: Bad value '" << argv[1] << "' for capacity." << std::endl;
return -1;
}
std::ifstream ifs(argv[2]);
if (ifs.is_open())
{
std::string description;
unsigned int weight;
unsigned int value;
int line = 1;
while (!ifs.eof())
{
if (!(ifs >> description))
{
std::cerr << "Error: Line number " << line << " does not contain 3 fields." << std::endl;
return -1;
}
if (!(ifs >> weight))
{
if (ifs.eof())
std::cerr << "Error: Line number " << line << " does not contain 3 fields." << std::endl;
else
std::cerr << "Error: Invalid weight '" << ifs << "' on line number " << line << "." << std::endl;
return -1;
}
else if (!(ifs >> weight) || (weight < 0))
{
std::cerr << "Error: Invalid weight '" << ifs << "' on line number " << line << "." << std::endl;
return -1;
}
if (!(ifs >> value))
{
if (ifs.eof())
std::cerr << "Error: Line number " << line << " does not contain 3 fields." << std::endl;
else
std::cerr << "Error: Invalid value '" << ifs << "' on line number " << line << "." << std::endl;
return -1;
}
else if (!(ifs >> value) || (value < 0))
{
std::cerr << "Error: Invalid value '" << ifs << "' on line number " << line << "." << std::endl;
return -1;
}
Item item = Item(line, weight, value, description);
items.push_back(item);
line++;
}
ifs.close();
knapsack(capacity, items, items.size());
}
else
{
std::cerr << "Error: Cannot open file '" << argv[2] << "'." << std::endl;
return -1;
}
return 0;
}
您使用的'.EOF()'作爲循環終止是錯誤的。使用'std :: getline(fi,inp);'代替。 (提升''std :: string inp;'退出循環。) – Casey
謝謝@Casey。儘管如此,我仍然展示了主要想法。 – Ultraviolet
謝謝你這篇文章@Md.SumsuddinShojib但是我仍然有一個問題,因爲delim是「,」而不是簡單的''字符。 – spicelord