對不起,這個「另一個」sscanf問題,但我找不到任何解決方案的實驗。sscanf說明符%[]和緩衝區溢出
這裏是一個字符串,我想分析和提取2子被分隔「:」:
char *str = "tag:R123:P1234";
這個函數做的工作:
char r_value[5];
char p_value[6];
sscanf(str, "tag:%[^:]:%s", r_value, p_value);
// now r_value = "R123" and p_value = "P1234"
但現在我要確保我將不會溢出我的接收緩衝區:
sscanf(str, "tag:%[^:]:%5s", r_value, p_value);
// this is good for p_value, if I give something bigger than 5 character long it
// will be truncated, if less than 5 character long, I get it also
但問題是%[]格式:
sscanf(str, "tag:%4[^:]:%5s", r_value, p_value);
// this will be ok if initial r_value is 4 char or less long
// but not OK if more than 4 char long, then it will be truncated,
// but p_value will not be found...
請注意我在嵌入式系統;我買不起非常大的緩衝區來提高溢出限制...
有沒有辦法解決我的問題?還是應該對每個字符執行手動循環以手動進行解析?
你不想問'sscanf',不要使用它。沒有它,還有很多其他的方式來做事情。 –
嘗試尋找['strtok()'函數](http://www.tutorialspoint.com/c_standard_library/c_function_strtok.htm) –