从printf格式字符串中提取类型信息

Extracting type info from printf format string

本文关键字:提取 取类型 信息 字符串 printf 格式      更新时间:2023-10-16

我想从printf格式字符串中提取c++类型信息。例如

Input: "%10u foo %% %+6.3f %ld %s"
Output:
  unsigned int
  double
  long
  char*

我已经尝试使用来自printf.h的parse_printf_format(),但是返回的argtypes似乎不包括关于signed/unsigned的信息。

是否有一些方法来获得签名/未签名的信息?

正如我在回答中所说的,parse_printf_format不是为您所需要的而创建的。您可以自己解析它,通过以下算法:

  1. 因为%后面的字符是修饰符或类型(不能两者都是),您首先在字符串
  2. 中搜索%字符
  3. 如果下一个字符是在数组类型('d', 's', 'f', 'g', 'u'等…),那么你得到的类型类(指针,int, unsigned, double等…)。这可能已经足够满足你的需求了。
  4. 如果没有,则继续查找下一个字符,直到找到一个在修饰符/类型数组中不允许的字符。
  5. 如果类型的类不足以满足你的需要,你必须回到修饰器来调整最终的类型。

对于真正的算法,您可以使用许多实现(例如boost),但是由于您不需要验证输入字符串,因此手工验证要简单得多。

伪代码:

const char flags[] = {'-', '+', '0', ' ', '#'};
const char widthPrec[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', '*'}; // Last char is an extension
const char modifiers[] = { 'h', 'l', 'L', 'z', 'j', 't' };
const char types[] = { '%', 'd', 'i', 'u', 'f', 'F', 'e', 'E', 'g', 'G', 'x', 'X', 'a', 'A', 'o', 's', 'c', 'p', 'n' }; // Last one is not wanted too
const char validChars[] = { union of all arrays above };
enum Type { None = 0, Int, Unsigned, Float, etc... };
Type typesToType[] = { None, Int, Int, Unsigned, Float, Float, ... etc... }; // Should match the types array above
// Expect a valid format, not validation is done
bool findTypesInFormat(string & format, vector<Type> types)
{
    size_t pos = 0;
    types.clear();
    while (pos < format.length())
    {
        pos = format.find_first_of('%', pos);
        if (pos == format.npos) break;
        pos++;
        if (format[pos] == '%') continue;
        size_t acceptUntilType = format.find_first_not_of(validChars, pos);
        if (pos == format.npos) pos = format.length();
        pos --;
        if (!inArray(types, format[pos])) return false; // Invalid string if the type is not what we support
        Type type = typesToType[indexInArray(types, format[pos])];
        // We now know the type, we might need to refine it
        if (inArray(modifiers, format[pos-1])
        {
            type = adjustTypeFromModifier(format[pos-1], type);
        }
        types.push_back(type);
        pos++;
    }
    return true;
}
// inArray, indexInArray and adjustTypeFromModifier are simple functions left to be written.