gpt4 book ai didi

c++ - 在可变参数函数中调用 snprintf 和 vsnprintf

转载 作者:行者123 更新时间:2023-11-28 04:17:08 31 4
gpt4 key购买 nike

我正在尝试在可变参数函数中使用可变参数函数。我在 Internet 和 Stack Overflow 上查看了很多示例,但找不到我的错误。

当我使用 Visual Studio 运行程序时,调用 snprintf 时发生访问冲突。

这里是标题:

#pragma once
#include <cstdarg>
class Console
{
public:
static void writeLine(const char *s, ...);

private:
Console() = delete;
~Console() = delete;
};

类(class):

#include "Console.h"
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <iostream>

void Console::writeLine(const char *s...)
{
va_list arg1, arg2;

// Search the total length
va_start(arg1, s);
va_copy(arg2, arg1);
int length = snprintf(nullptr, 0, s, arg1);
va_end(arg1);

size_t size = length + 1;
char *szBuff = new char[size]; // note +1 for terminating null byte

// Format the string
vsnprintf(szBuff, size, s, arg2);
va_end(arg2);

std::cout << (const char*)szBuff << std::endl;

delete(szBuff);
}

和主程序:

#include "Console.h"
#include <iostream>

int main()
{
Console::writeLine("Example with an int (%d) and a string(%s)", 10, "my string");
}

我确定我做了一个愚蠢的事情,但我不明白为什么它不起作用。

编辑

cout 调用只是一个示例,我正在使用 Windows 中的函数写入 Visual Studio 的控制台。这就是为什么,我正在上这门课:在将结果写入控制台之前格式化数据。

最佳答案

您使用了错误的函数来计算缓冲区的大小。 snprintf() 不将 va_list 作为输入。此外,Microsoft 的 vsnprintf() 实现并未定义为接受 NULL 缓冲区作为输入,就像 snprintf() 那样。您需要改用 _vscprintf():

_vscprintf returns the number of characters that would be generated if the string pointed to by the list of arguments was printed or sent to a file or buffer using the specified formatting codes. The value returned does not include the terminating null character.

此外,您没有正确释放缓冲区。由于您使用 new[] 来分配它,因此您需要使用 delete[] 来释放它。

试试这个:

void Console::writeLine(const char *s, ...)
{
va_list arg1, arg2;

va_start(arg1, s);

// Search the total length
va_copy(arg2, arg1);
size_t size = _vscprintf(s, arg2) + 1; // note +1 for terminating null byte
va_end(arg2);

char *szBuff = new char[size];

// Format the string
vsnprintf(szBuff, size, s, arg1);

va_end(arg1);

std::cout << szBuff << std::endl;

delete[] szBuff;
}

关于c++ - 在可变参数函数中调用 snprintf 和 vsnprintf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56331128/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com