【问题标题】:Calling functions from a text file从文本文件调用函数
【发布时间】:2019-03-02 09:36:23
【问题描述】:

当在main.cpp while 循环中读取它们时,我正在尝试从test.txt 调用fAfB

test.txt

fA()
fB("fB")

main.cpp

#include <iostream>
#include <fstream>
#include <string>

void fA() {
    std::cout << "fA called" << std::endl;
}

void fB(std::string b) {
    std::cout << b << std::endl;
}

int main() {
    std::ifstream file;
    file.open("test.txt");
    if (file.is_open()) {
        std::string line;
        while (std::getline(file, line))
            std::cout << line << std::endl;
    }
    file.close();
}

尽管fAfB 做类似的事情并且可以在示例中编写为一个函数,但实际上这些函数可以做完全不同的事情。因此我需要按名称调用该函数。

调用者具有带有参数类型的函数声明。

没有库,除了 STL。

【问题讨论】:

标签: c++


【解决方案1】:

一个建议,我用map来方便添加更多功能

#include <iostream>
#include <fstream>
#include <string>
#include <map>

void fA() {
    std::cout << "fA called" << std::endl;
}

void fB(std::string b) {
    std::cout << "fB(" << b << ") called" << std::endl;
}

int main() {
    std::ifstream file;
    file.open("test.txt");
    if (file.is_open()) {
      std::string line;

      while (std::getline(file, line)) {
        size_t p1, p2;

        if (((p1 = line.find('(')) == std::string::npos) ||
            ((p2 = line.find(')', p1+1)) == std::string::npos)) // can check last char is ')' too
          std::cout << "invalid line" << line << std::endl;
        else {
          std::string fn = line.substr(0, p1);

          static const std::map<std::string, void (*)()> noarg = { {"FA", fA} };
          static const std::map<std::string, void (*)(std::string)> stringarg = { {"FB", fB} };

          std::map<std::string, void (*)()>::const_iterator itno = noarg.find(fn);
          std::map<std::string, void (*)(std::string)>::const_iterator itstr = stringarg.find(fn);

          if ((itno = noarg.find(fn)) != noarg.end())
            // may check there is no arg in call
            itno->second();
          else if ((itstr = stringarg.find(fn)) != stringarg.end()) {
            if (((p1 = line.find('"', p1+1)) == std::string::npos) ||
                ((p2 = line.find('"', p1+1)) == std::string::npos))
              std::cout << "no string arg in " << line << std::endl;
            else
              // may check there is only one arg
              itstr->second(line.substr(p1+1, p2 - p1 -1));
          }
          else
            std::cout << "unmanaged function " << fn << std::endl;
        }
      }
    }

    file.close();
}

编译和执行:

pi@raspberrypi:/tmp $ g++ -pedantic -Wextra f.cc
pi@raspberrypi:/tmp $ cat test.txt 
FA()
FB("aze")
FC
FC(
FC()
FB(123)
pi@raspberrypi:/tmp $ ./a.out
fA called
fB(aze) called
invalid lineFC
invalid lineFC(
unmanaged function FC
no string arg in FB(123)

【讨论】:

    猜你喜欢
    • 2013-01-09
    • 2016-07-07
    • 1970-01-01
    • 1970-01-01
    • 2015-11-13
    • 2015-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多