C ++ _snprintf返回-1

时间:2017-04-10 11:22:18

标签: c++ printf

我对_snprintf函数有一个奇怪的问题, 代码:

string format(const char *fmt, ...)
{
    string result;

    va_list vl1, vl2;
    va_start(vl1, fmt);
    va_copy(vl2, vl1);

    int needen_size = _vsnprintf(nullptr, 0, fmt, vl1);
    if (needen_size > 0)
    {
        if (char *buffer = new char[needen_size + 1]) {
            _vsnprintf(buffer, needen_size, fmt, vl2);
            buffer[needen_size] = '\0';
            result.assign(buffer);
            delete[] buffer;
        }
    }

    va_end(vl1);
    va_end(vl2);

    return result;
}

对我来说它返回-1,但为什么呢? 在文档中说-1发生编码错误时返回,但我没有编码任何东西,没有unicode格式化? 我只需要长度值来扩展缓冲区

我也尝试了一个_snprintf_s导致断言,但必须返回一个needen长度

另外我不能拿足够大的缓冲区,因为string1,string2,string3可以是实际情况下的任何字符串

谢谢

编辑: 在Visual Studio 2013和2015中为我工作的最终解决方案 EDIT2: 修复了va_list的使用(谢谢mch)

<ng-form name="form" ng-submit="submit()">
 <div class="inputblock">
<span class="input-icon"><img src="images/office-icon.png"></span>
<input type="text" class="with-icon" placeholder="Work MainStreet" ng-model="workmainstreet" required="" name="workmainstreet">
<span ng-show="form.$submitted || form.workmainstreet.$touched" class="error-message">
<span style="color:red" ng-show="form.workmainstreet.$error.required">Please Enter Work MainStreet</span>
</span>
</div>
<div class="inputblock">
<span class="input-icon"><img src="images/office-icon.png"></span>
<input type="text" class="with-icon" placeholder="Work SubStreet" ng-model="worksubstreet" required="" name="worksubstreet">
<span ng-show="form.$submitted || form.worksubstreet.$touched" class="error-message">
<span style="color:red" ng-show="form.worksubstreet.$error.required">Please Enter Work SubStreet</span>
</span>
</div>
 <div class="button-container">
<input type="submit" value="Cancel" id="input-cancel">
<input type="submit" ng-disabled="form.worksubstreet.$dirty && form.worksubstreet.$invalid || form.workmainstreet.$dirty && form.workmainstreet.$invalid" ng-click="RegisterUser()" value="Submit" id="input-submit"/>
</div>
</ng-form>

1 个答案:

答案 0 :(得分:2)

当您为指针传递零并且为指针传递NULL时,它将返回您必须分配的内容/缓冲区大小:

char string1[] = "string";
char string2[] = "Description";
char string3[] = "BIOS Date: 05/12/15 15:30:43 Ver: 04.06.05";

resx = _snprintf(NULL, 0, "[%03u] %s %s = (%s)", 16, string1, string2, string3);

然后再次调用正确的大小

char *buffer = new char[resx+1];

int resx = _snprintf(buffer, resx, "[%03u] %s %s = (%s)", 16, string1, string2, string3);