首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >杂货店项目C++,迭代一个文件

杂货店项目C++,迭代一个文件
EN

Stack Overflow用户
提问于 2022-02-17 13:50:00
回答 1查看 55关注 0票数 -1

我遇到了一些问题,试图找出如何执行这个特定的方法,迭代一个文本文件,跟踪一个项目出现多少次,同时不超过一次打印该项,例如,输出如下:

代码语言:javascript
复制
Broccoli 2
Peas 4
Bananas 1
etc.

列出的python只是为了测试,直方图必须用python编写,但我现在还不担心。

MAIN.CPP

代码语言:javascript
复制
#include <Python.h>
#include <iostream>
#include <Windows.h>
#include <cmath>
#include <string>
#include <fstream>

using namespace std;

void CallProcedure(string pName)
{
    char* procname = new char[pName.length() + 1];
    std::strcpy(procname, pName.c_str());

    Py_Initialize();
    PyObject* my_module = PyImport_ImportModule("python");
    PyErr_Print();
    PyObject* my_function = PyObject_GetAttrString(my_module, procname);
    PyObject* my_result = PyObject_CallObject(my_function, NULL);
    Py_Finalize();

    delete[] procname;
}

int callIntFunc(string proc, string param)
{
    char* procname = new char[proc.length() + 1];
    std::strcpy(procname, proc.c_str());

    char* paramval = new char[param.length() + 1];
    std::strcpy(paramval, param.c_str());


    PyObject* pName, * pModule, * pDict, * pFunc, * pValue = nullptr, * presult = nullptr;
    
    Py_Initialize();
    
    pName = PyUnicode_FromString((char*)"python");
    
    pModule = PyImport_Import(pName);
    
    pDict = PyModule_GetDict(pModule);
     
    pFunc = PyDict_GetItemString(pDict, procname);
    if (PyCallable_Check(pFunc))
    {
        pValue = Py_BuildValue("(z)", paramval);
        PyErr_Print();
        presult = PyObject_CallObject(pFunc, pValue);
        PyErr_Print();
    }
    else
    {
        PyErr_Print();
    }
    
    Py_DECREF(pValue);
    
    Py_DECREF(pModule);
    Py_DECREF(pName);
    
    Py_Finalize();

     
    delete[] procname;
    delete[] paramval;


    return _PyLong_AsInt(presult);
}

int callIntFunc(string proc, int param)
{
    char* procname = new char[proc.length() + 1];
    std::strcpy(procname, proc.c_str());

    PyObject* pName, * pModule, * pDict, * pFunc, * pValue = nullptr, * presult = nullptr;
    
    Py_Initialize();
    
    pName = PyUnicode_FromString((char*)"python");
    
    pModule = PyImport_Import(pName);
    
    pDict = PyModule_GetDict(pModule);
     
    pFunc = PyDict_GetItemString(pDict, procname);
    if (PyCallable_Check(pFunc))
    {
        pValue = Py_BuildValue("(i)", param);
        PyErr_Print();
        presult = PyObject_CallObject(pFunc, pValue);
        PyErr_Print();
    }
    else
    {
        PyErr_Print();
    }

    Py_DECREF(pValue);

    Py_DECREF(pModule);
    Py_DECREF(pName);
    
    Py_Finalize();
 
    delete[] procname;

    return _PyLong_AsInt(presult);
}

void displayItemsPurchased() {
    //FINISH
}

void displaySpecificItem() {
    ifstream fin("Items.txt");
    int count = 0;
    char ch[20], item[20];
    cout << "Enter an item to display: ";
    cin >> item;
    while (fin) {
        fin >> ch;
        if (strcmp(ch, item) == 0)
            count++;
    }
    cout << item << " was bought " << count << " times today";
    fin.close(); 
}

void displayHistogram() {
    //FINISH
}

void displayMenu() {
    int userChoice;
    int i = 0;
    while (i == 0) {
        cout << endl;
        cout << "***********************************************" << endl;
        cout << "1 - Display List all items purchased          *" << endl;
        cout << "2 - Get quantity of a specific item purchased *" << endl;
        cout << "3 - Display items purchased with a histogram  *" << endl;
        cout << "4 - Exit                                      *" << endl;
        cout << "***********************************************" << endl;
        cout << "Selection: ";
        cin >> userChoice;
        cout << endl;

        if (userChoice == 1) {
            displayItemsPurchased();
            cout << endl;
        }
        else if (userChoice == 2) {
            displaySpecificItem();
            cout << endl;
        }
        else if (userChoice == 3) {
            cout << "You selected 3";
            cout << endl;
        }
        else if (userChoice == 4) {
            exit(0);
        }
        else {
            cout << "Invalid selection. Try again." << endl;
        }
    }
}

void main()
{
    CallProcedure("printsomething");
    cout << callIntFunc("PrintMe", "House") << endl;
    cout << callIntFunc("SquareValue", 2);
    displayMenu();
    
    system("pause>0");
}

PYTHON.PY

代码语言:javascript
复制
import re
import string


def printsomething():
    print("Hello from python!")

def PrintMe(v):
    print("You sent me: " + v)
    return 100;

def SquareValue(v):
    return v * v

ITEMS.TXT

代码语言:javascript
复制
Spinach

Radishes

Broccoli

Peas

Cranberries

Broccoli

Potatoes

Cucumbers

Radishes
Cranberries

Peaches

Zucchini

Potatoes

Cranberries

Cantaloupe

Beets

Cauliflower

Cranberries

Peas

Zucchini

Peas

Onions

Potatoes

Cauliflower

Spinach

Radishes

Onions

Zucchini

Cranberries

Peaches

Yams

Zucchini

Apples

Cucumbers

Broccoli

Cranberries

Beets

Peas

Cauliflower

Potatoes

Cauliflower

Celery

Cranberries

Limes

Cranberries

Broccoli

Spinach

Broccoli

Garlic

Cauliflower

Pumpkins

Celery

Peas

Potatoes

Yams

Zucchini

Cranberries

Cantaloupe

Zucchini

Pumpkins

Cauliflower

Yams

Pears

Peaches

Apples

Zucchini

Cranberries

Zucchini

Garlic

Broccoli

Garlic

Onions

Spinach

Cucumbers

Cucumbers

Garlic

Spinach

Peaches

Cucumbers

Broccoli

Zucchini
Peas

Celery

Cucumbers

Celery

Yams

Garlic

Cucumbers

Peas

Beets

Yams

Peas

Apples

Peaches

Garlic

Celery

Garlic

Cucumbers

Garlic

Apples

Celery

Zucchini

Cucumbers

Onions

我需要帮助的方法是displayItemsPurchased()方法

EN

回答 1

Stack Overflow用户

发布于 2022-02-17 14:21:19

您只需使用fstream就可以很容易地在C++中完成这样的操作:

代码语言:javascript
复制
#include <iostream>
#include <string>
#include <vector>
#include <fstream>

int main()
{
    std::ifstream in("input.txt");

    std::vector<std::string> item_names;
    std::vector<int> item_counts;

    std::string line;
    while (std::getline(in, line))
    {
        if (line.empty()) continue;

        item_names.push_back(line);
        item_counts.push_back(1);

        for (int i = 0; i < item_names.size() - 1; i++)
        {
            if (line == item_names[i])
            {
                item_counts[i]++;
                item_names.pop_back();
                item_counts.pop_back();

                break;
            }
        }
    }

    for (int i = 0; i < item_names.size(); i++)
    {
        std::cout << i + 1 << ". " << item_names[i] << ": " << item_counts[i] << std::endl;
    }
}

此代码读取存储在"input.txt“中的数据,然后打印出"input.txt”中所有项的出现次数。

例如,

input.txt

代码语言:javascript
复制
Spinach
Radishes
Broccoli
Peas
Cranberries
Broccoli
Potatoes
Cucumbers
Radishes
Cranberries
Peaches
Zucchini
Potatoes
Cranberries
Cantaloupe
Beets
Cauliflower
Cranberries

输出

代码语言:javascript
复制
1. Spinach: 1
2. Radishes: 2
3. Broccoli: 2
4. Peas: 1
5. Cranberries: 4
6. Potatoes: 2
7. Cucumbers: 1
8. Peaches: 1
9. Zucchini: 1
10. Cantaloupe: 1
11. Beets: 1
12. Cauliflower: 1

这一问题的解决方案也在评论中给出,而且要小得多。但是它并不是从任何.txt文件中读取的。相反,它直接从用户那里获取输入。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71159382

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档