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

How to print the value stored in an char[] or string in the program itself

本文关键字:字符串 char 打印 程序 存储      更新时间:2023-10-16

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

是否可以在程序本身上打印字符串或整数的值?例如 - 我已经为一个程序编写了 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 0n");
}
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 0n");
}
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;
}

您可以创建一个函数指针数组,并在循环中调用每个指针。

例:

#include <stdio.h>
void test_0()
{
    printf("Test 0n");
}
void test_1()
{
    printf("Test 1n");
}
void test_2()
{
    printf("Test 2n");
}
int main()
{
    void(*a)() = test_0;
    void(*b)() = test_1;
    void(*c)() = test_2;
    const int SIZE = 3;
    void(*arr[SIZE])() = {
        { a }, { b }, { c }
    };
    for (int i = 0; i < SIZE; ++i) {
        arr[i]();
    }
    return 0;
}

输出:

Test 0
Test 1
Test 2
相关文章: