gpt4 book ai didi

c++ - 如何在程序本身中打印存储在 char[] 或字符串中的值

转载 作者:行者123 更新时间:2023-11-30 19:12:19 24 4
gpt4 key购买 nike

有人尝试过这样的事情吗?

是否可以在程序本身上打印字符串或整数的值?举例来说 - 我已经为一个程序编写了 2 个测试,我试图通过在 for 循环中循环来调用所有测试函数。

一个小示例

#define MAX_TESTS 10


for(test_idx = 0; test_idx<MAX_TESTS; ++test_idx)
{
test_##test_idx();

//Here the output will be more like "test_test_idx();"
//But I am looking for something like
//"test_0();"
//"test_1();"
//"test_2();"
.
.
.
//"test_9();"
}

有没有办法用C语言实现?

<小时/>

完整的程序

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//Macros
#define MAX_TEST 2
#define _MYCAT(a,b) a##b()

void test_0()
{
printf("Test 0\n");
}

void test_1()
{
printf("Test 1 \n");
}

int main()
{
printf("Max Product Testing \n");

for (int test_idx=0; test_idx<MAX_TEST; ++test_idx)
{
/* Try - 1
char buffer[50];
int n = sprintf(buffer, "test_%d", test_idx);
printf("%s %d \n", buffer, n);
*/

//Try - 2
//_MYCAT(test_, test_idx);
}
return 0;
}

最佳答案

C++中你可以得到的壁橱是保存函数名称到函数的映射,如下所示:

#include <iostream>
#include <unordered_map>
#include <string>
#include <functional>
using namespace std;

void test_0()
{
printf("Test 0\n");
}

void test_1()
{
printf("Test 1 \n");
}

int main() {
unordered_map<string, function<void()>> func_map;
func_map["test_0"] = test_0;
func_map["test_1"] = test_1;

for(int i = 0; i < 2; ++i) {
func_map.at("test_" + to_string(i))();
}

return 0;
}

关于c++ - 如何在程序本身中打印存储在 char[] 或字符串中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37328895/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com