簡體   English   中英

從printf格式字符串中提取類型信息

[英]Extracting type info from printf format string

我想從printf格式字符串中提取c ++類型信息。 例如,

Input: "%10u foo %% %+6.3f %ld %s"

Output:
  unsigned int
  double
  long
  char*

我已經嘗試使用來自printf.h的parse_printf_format() ,但是返回的argtypes似乎不包含有關已簽名/未簽名的信息。

有沒有辦法獲取簽名/未簽名的信息?

正如我在回答中所說的那樣,parse_printf_format不是為您所需的。 您可以通過以下算法自己解析它:

  1. 由於%后的char是修飾符或類型(不能同時為兩者),因此您首先在字符串中搜索% char
  2. 如果下一個字符位於類型數組(“ d”,“ s”,“ f”,“ g”,“ u”等)中,則您將得到該類型的類(指針,整數,無符號) ,double等)。 這可能足以滿足您的需求。
  3. 如果不是,則繼續下一個字符,直到找到修飾符/類型數組中不允許的一個字符。
  4. 如果該類型的類不足以滿足您的需要,則必須返回到修飾符以調整最終類型。

您可以對正版算法使用多種實現方式(例如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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM