编写一个函数从文件中读取数字并求和

Write a function to read and sum number from a file C++

本文关键字:文件 读取 数字 求和 函数 一个      更新时间:2023-10-16

文件是这样的:

tucanos 10
tacobell 5
tucanos 5
pizzahut 15
tucanos 5
pizzahut 2
tucanos 5

其中字符串是餐厅的名字,数字是它的点赞数。我应该从阅读文件中找出每个餐厅的喜欢数量的总和,但我不知道如何做到这一点。你们有人能给我点提示吗?

首先,这里有一个很好的函数,将std::string拆分为std::vector,给定分隔符字符:

std::vector<std::string> &split(const std::string &s, 
    char delim, std::vector<std::string> &elems) {
        std::stringstream ss(s);
        std::string item;
        while (std::getline(ss, item, delim)) {
            elems.push_back(item);
        }
        return elems;
}

接下来,我们可以使用下面的代码实现预期的结果:

int main(int argc, char** argv) {
    std::map<std::string, int> map;
    std::ifstream file("file_with_string.txt", std::ifstream::in);
    std::string temp;
    while (std::getline(file, temp)) {
        std::cout << temp << "n";
        std::vector<std::string> tokens;
        tokens = split(temp, ' ', tokens);
        for (std::vector<std::string>::iterator it = tokens.begin(); 
             it != tokens.end(); it++) {
            std::vector<std::string>::iterator it1 = it;
            std::map<std::string, int>::iterator mapIt = map.find(*it++);
            int number;
            std::istringstream(*it) >> number;
            if (mapIt != map.end()) {
                (mapIt->second) += (number);
            } else {
                map[*it1] = number;
            }
        }
    }
    for (std::map<std::string, int>::iterator it = map.begin(); 
         it != map.end(); it++) {
        std::cout << it->first << " " << it->second << "n";
    }
    return 0;
}

tucanos 10 tacobell 5 tucanos 5 pizzahut 15 tucanos 5 pizzahut 2 tucanos 5

pizzahut 17

tacobell 5

tucanos 25

运行成功(总时间:55ms)


我们可以使它更简单

    std::map<std::string, int> map;
    std::ifstream infile("file_with_string.txt",std::ifstream::in);
    std::string resturant = "";
    int likes = 0;
    while(infile >> resturant >> likes ){
            map[resturant ] += likes ;
    }

但是第一个版本提供了更多关于迭代器的见解,如何遍历std::map, std::vector以及如何填充map。

下面是一些伪代码:

Open file
For each restaurant-likes pair
    Read restaurant-likes pair from file
    If first time we've seen a restaurant
        Add restaurant to list
    Lookup restaurant in list and add likes to total for that restaurant
End For
Close file
Print all restarants and total likes

使用fscanf解析来自文件的输入,然后应用添加操作。示例

// c:tempnameofexecutable.exe < yourtextfile.txt
#include <iostream>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
int main()
{
    string              resturant; 
    int                 likes;
    map<string, int>    likesCount;
    while (cin >> resturant >> likes) {
        likesCount[resturant] += likes;
    }
    for_each(begin(likesCount), end(likesCount),  [&](pair<string,int> x){
        cout << x.first << " " << x.second << endl;
    }); 
    //// using plain for instead of std::for_each 
    //for (auto i = begin(likesCount); i != end(likesCount); i++)   {
    //  cout << i->first << " " << i->second << endl;
    //}

}

也许可以帮助你:

#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <iterator>
int
main() {
        std::map<std::string, int> count;
        std::ifstream infile("cars.dat", std::ios::in);
        if (infile == NULL) {
                fprintf(stderr, "Failed to open file.n");
                exit(-1);
        }
        std::string resturant = "";
        int likes = 0;
        while(infile >> resturant >> likes ){
                count[resturant ] += likes ;
        }
        printf("--------------------each sum-------------------n");
        std::map<std::string, int>::iterator it(count.begin());
        for (; it != sum.end(); ) {
                printf("%s %dn", (it->first).c_str(),it->second);
                it++;
        }
        infile.close();
        return 0;
}

结果:-------------------- 每一笔 -------------------pizzahut 17tacobell 5tucanos 25