比较c中的char

前端之家收集整理的这篇文章主要介绍了比较c中的char前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是我正在从中获取数据的文本文件
10
wood      8
gold      7
silver    5
gold      9
wood      1
silver    1
silver    9
wood      3
gold      5
wood      7

我应该找到具有相同名称的商品并添加所有金额,因此最终结果应为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;
}

到目前为止的问题是名称[i] ==名称[d]甚至没有反应,例如名称[i] =“wood”和名称[d] =“wood”

解决方法

@H_403_13@ 在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;
}

顺便说一下,您可以使用std::pair,使您的代码更具可读性,其中第一个成员是名称,第二个成员是金额.

与您的问题无关,main()往往返回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;
}

输出

Georgioss-MacBook-Pro:~ gsamaras$g++ -Wall -std=c++0x main.cpp 
Georgioss-MacBook-Pro:~ gsamaras$./a.out 
RESULTS:
wood 19
gold 21
silver 15
原文链接:https://www.f2er.com/c/110328.html

猜你在找的C&C++相关文章