Mah*_*hok 6 c++ arrays string comparison char
这是我正在从中获取数据的文本文件
10
wood 8
gold 7
silver 5
gold 9
wood 1
silver 1
silver 9
wood 3
gold 5
wood 7
Run Code Online (Sandbox Code Playgroud)
我应该找到具有相同名称的商品并添加所有金额,因此最终结果应为wood = 19; 金= 21; 银= 15.这就是我到目前为止所做的
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream read("data.txt");
int n;
read >> n;
char name[10][n]; // 10 symbols are given for items name
int amount[n];
for(int i=0; i<n; i++)
{
read.ignore(80, '\n');
read.get(name[i], 10);
read >> amount[i];
}
for(int i=0; i<n; i++)
{
for(int d=1; d<n; d++)
{
if(name[i]==name[d] && i!=d)
{
}
}
}
return 1;
}
Run Code Online (Sandbox Code Playgroud)
问题至今是name[i]==name[d]没有反应,甚至是例如name[i]="wood"和name[d]="wood"
在C++中,我们倾向于使用std::string过char[].第一个是等于运算符重载,因此你的代码应该工作.有了后者,你需要strcmp()实现自己的目标.
现在你的代码可能是这样的(我使用了std :: vector,但你可以使用一个字符串数组,但我不推荐它):
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
ifstream infile("data.txt");
int n;
infile >> n;
vector<string> name(n);
int amount[n], i = 0;
while (infile >> name[i] >> amount[i])
{
cout << name[i] << " " << amount[i] << endl;
i++;
}
// do your logic
return 0;
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,您可以使用std::pair,使您的代码更具可读性,第一个成员是名称,第二个成员是金额.
与你的问题无关,main()往往是return 0;一切都很好,而你返回1.
PS:这是一个有效的例子:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <utility>
using namespace std;
int main()
{
ifstream infile("data.txt");
int n;
infile >> n;
vector<string> name(n);
int amount[n], i = 0;
while (infile >> name[i] >> amount[i])
{
// cout << name[i] << " " << amount[i] << endl;
i++;
}
vector< pair<string, int> > result;
bool found;
for(int i = 0; i < name.size(); ++i)
{
found = false;
for(int j = 0; j < result.size(); ++j)
{
if(name[i] == result[j].first)
{
result[j].second += amount[i];
found = true;
}
}
if(!found)
{
result.push_back({name[i], amount[i]});
}
}
cout << "RESULTS:\n";
for(int i = 0; i < result.size(); ++i)
cout << result[i].first << " " << result[i].second << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
Georgioss-MacBook-Pro:~ gsamaras$ g++ -Wall -std=c++0x main.cpp
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out
RESULTS:
wood 19
gold 21
silver 15
Run Code Online (Sandbox Code Playgroud)