c ++ win32:基本字符串处理

时间:2013-10-24 02:38:24

标签: c++ winapi

刚刚在Visual Studio 2012中使用win32跳转到c ++。我在C和C#方面经验丰富,但我的c ++有点缺乏。 win32的东西似乎只是带着任何直觉的暗示并把它扔进火山。到目前为止,这是一个痛苦。

以下是我要做的事情: 1)从文本框“编辑”控件中提取文本 2)将此文本转换为int 3)使用sprintf类型格式化器为双浮点数形成一个字符串 4)获取结果字符串并将其显示在不同的文本框中。

我已经尝试了几种我在网上发现的不同的东西,但它们都很简短。这是我能做的最好的事情:

wchar_t buffer[30];
const wchar_t formatString[] = {'%','f','\0'}; //Yes I know this is awful, I don't know how to       convert a string literal into a wchar_t array.

GetWindowText(txtFixedPtToFloatInputHandle, &buffer[0], 15);

//Convert to signed integer
fixedPtValue = _wtoi(&buffer[0]);

//get a float
floatVal = 12.50;

//Use formatter to create a string representation
swprintf(buffer,  30, &formatString[0], floatVal);

SetWindowText(txtFixedPtToFloatOutputHandle, buffer);

这是我最接近的。我知道这很讨厌,但我在网上找到的所有其他东西都不尽如人意(LPWSTR,boost ::,stdio.h)。在此代码中,所有缓冲区都加载了正确的字符串!问题是我的程序在函数返回时关闭/退出!任何帮助?

1 个答案:

答案 0 :(得分:2)

如果您希望能够构建ANSI版本和UNICODE版本,可以使用Generic-Text Mappings in Tchar.h

#include <tchar.h>

_TCHAR EditText[ 32 ];
int cbCopied = GetWindowText( hWndInput, EditText, sizeof( EditText ) / sizeof( _TCHAR ) );
// Eventually use GetLastError if cbCopied == 0

// -1 because the snprint familly functions do not write a 0 if len == count, see docs
size_t cbMaxCarToOutput = ( sizeof( EditText ) / sizeof( _TCHAR ) ) - 1;
_sntprintf( EditText, cbMaxCarToOutput, _TEXT( "%f" ), floatVal );

SetWindowText( hWndInput, EditText );