error C2664: “OutputDebugStringW”: 不能将参数 1 从“char [1024]”转换为“LPCWSTR”

本文详细解析了C++中字符类型转换问题导致的错误信息,并提供了解决方法,即使用OutputDebugStringA()替代OutputDebugString()。文章解释了错误产生的原因,并给出了设置工程属性使用MBCS编码集的建议。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文地址::http://www.verydemo.com/demo_c230_i4355.html


错误信息:error C2664: 'OutputDebugStringW' : cannot convert parameter 1 from 'char [100]' to 'LPCWSTR'
1>        Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast

相关代码:

  if(i>1){ 
   sprintf(msg,"1+...+%d=%d\n",i,sum); 
   OutputDebugString(msg); 
  }

找了一天资料,原因锁定在字符的转换问题,搞版本的vs中,OutputDebugString要求一个wchar_t

而不是char,而sprintf则需要char参数,那我们是不是一定要通过字符转换解决问题呢?

 

答案就是 OutputDebugStringA()

原因:

默认是Unicode方式,OutputDebugString会变成OutputDebugStringW。如果想用ANSI版本的,直接写OutputDebugStringA,或者设置工程属性,使用MBCS的编码集。

// 增强的日志输出函数 宽字符版本 void OutputLogW(const wchar_t* format, ...) { // 获取当前时间 auto now = std::chrono::system_clock::now(); auto now_time = std::chrono::system_clock::to_time_t(now); auto now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000; // 格式化时间 std::wstringstream time_ss; time_ss << std::put_time(std::localtime(&now_time), L"%Y-%m-%d %H:%M:%S") << L"." << std::setfill(L'0') << std::setw(3) << now_ms.count(); // 提取文件名(不含路径) // std::wstring filename(file); // size_t pos = filename.find_last_of(L"\\/"); // if (pos != std::wstring::npos) { // filename = filename.substr(pos + 1); // } // 处理变参数 va_list args; va_start(args, format); // 获取变参长度 int len = _vscwprintf(format, args) + 1; // +1 for '\0' if (len <= 0) { va_end(args); return; } // 分配缓冲区 std::wstring buffer; buffer.resize(len); vswprintf_s(&buffer[0], len, format, args); buffer.resize(len - 1); // 移除末尾的null va_end(args); // 构建完整日志消息 std::wstringstream fullMsg; fullMsg << L"[" << time_ss.str() << L"] " << L"[" << file << L":" << line << L"] " << L"[" << function << L"] " << buffer; // 输出到控制台 std::wcerr << fullMsg.str() << std::endl; // 输出到调试器(Windows) #ifdef _WIN32 OutputDebugStringW(fullMsg.str().c_str()); OutputDebugStringW(L"\n"); #endif }完善为日志宏定义为准 #define LOGW(...) OutputLogW(L"[%s:%s:%d] %s",__FILE__, __FUNCTION__, __LINE__, __VA_ARGS__)
最新发布
08-10
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值