嘿家伙我有一个关于我的代码的问题。以下是我们必须做的: “让用户阅读文件,该文件的格式与网站上的”items.txt“格式相同 将始终是一个具有名称和价格的项目列表如果一个 物品的配方不存在,制作该物品的唯一方法就是直接购买它。制作一个程序,读取所有物品和配方 ,然后说明可以获得多少利润通过制作每件物品 如果一件物品没有配方,您会购买该物品,然后以相同的价格转售它,并从中获利 0.如果物品确实有配方,您将购买材料以制作此物品并从最终产品的价格中扣除 的成本 每件商品只有零个或一个配方,这些商品将始终为b首先列出。 项目的名称将始终为单个单词(使用_加入通常为多个单词的名称)。您 可以假设会有小于50项和每个配方将使用其他不到50个项目,以创建一个 最终产品。”字符串双向转换没有sstream或boost词法转换
这是items1.txt我们使用
Item: Wood 2.5
Item: Metal 5.5
Item: Cat 900
Item: Spear 50.7
Recipe: Spear = Wood + Wood + Metal ;
我有我认为会工作,但我不能得到一个工作线,我试图用stod,但显然我的学校的电脑不支持它,我也尝试了提高词法演员,这也不起作用
它说“stod:没有在这个范围内声明。
这里是我的代码:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <algorithm>
#include <sstream>
using namespace std;
string nextstring(string str, int start_index);
int split(string str, string a[], int max_size);
int main()
{
ifstream in_stream;
string fileName;
cout << "Enter the file name : ";
cin >> fileName;
in_stream.open(fileName.c_str());
//error checking
if (in_stream.fail())
{
cout << "File could not be opened." << endl;
exit(1);
}
string items[50];
double items_value[50];
string recipe[50];
string rname = recipe[0];
double profit = 0;
int j = 0;
string lines;
int number_of_lines = 0;
while(getline(in_stream, lines))
{
if(lines.substr(0,5) == "Item:")
{
int beginning = lines.find_first_of(' ') + 1;
int next_space = lines.find(" ", beginning);
items_value[j] = stod(lines.substr(next_space));
items[j] = lines.substr(beginning,lines.find_first_of(' ', beginning) - beginning);
j++;
}
if(lines.substr(0,7) == "Recipe:")
{
int max_size = lines.length();
int cnt = split(lines,recipe,max_size);
double profit1 = 0;
double profit2 = 0;
for(int j = 3; j < cnt; j++)
{
for(int i = 0; i < 4; i++)
{
if((recipe[j] == items[i]) && (recipe[j] != "+")&& (recipe[j] != ";"))
{
cout << "Making " << items[i] << ", " << "profit = 0" << endl;
profit1 += items_value[i];
}
if(recipe[1] != items[i])
{
profit2 = 0;
}
}
}
for(int i = 0; i < cnt; i++)
{
if((recipe[1] == items[i]))
{
profit = items_value[i];
cout << "Making " << items[i] << ", " << "profit = ";
}
}
cout << profit - profit1 << endl;
}
}
in_stream.close();
return 0;
}
string nextstring(string str, int start_index)
{
int y =0;
y = str.find(' ',start_index);
y = y-start_index;
str = str.substr(start_index,y);
return str;
}
int split(string str, string a[], int max_size)
{
int i;
int num = 0;
for (i=0; i<max_size; i++)
{
a[i] = nextstring(str,num);
num = num + a[i].length() + 1;
if(num >= str.length())
{
i++;
break;
}
}
return i;
}
尝试启用C++ 11(检查你的编译器/ IDE的文档,了解如何做到这一点)。为了将来的参考,请减少不必要的绒毛,这个问题中几乎所有的东西都不是真的需要证明这个问题。这里有更多的信息([问])和这里([mcve])。 –