CString str = _T("CSFS dfdfd");
TCHAR szBuff[100] = {0};
TCHAR szBuff2[100] = {0};
swscanf_s(str.GetBuffer(), _T("%s%s"), szBuff, szBuff2);上述代码执行到swscanf_s函数时为何产生异常?
而把swscanf_s函数换成_stscanf函数就没异常,为什么?
msdn说swscanf_s函数比_stscanf函数更安全,可是为何swscanf_s函数会异常?
我试过好多次了,发现swscanf_s函数只要用%s做格式符,都会异常。异常信息如下:0xfdfdfdfd 处最可能的异常: 0xC0000005: 读取位置 0xfdfdfdfd 时发生访问冲突
高手解释下,难道swscanf_s函数就不能用%s做格式符?
TCHAR szBuff[100] = {0};
TCHAR szBuff2[100] = {0};
swscanf_s(str.GetBuffer(), _T("%s%s"), szBuff, szBuff2);上述代码执行到swscanf_s函数时为何产生异常?
而把swscanf_s函数换成_stscanf函数就没异常,为什么?
msdn说swscanf_s函数比_stscanf函数更安全,可是为何swscanf_s函数会异常?
我试过好多次了,发现swscanf_s函数只要用%s做格式符,都会异常。异常信息如下:0xfdfdfdfd 处最可能的异常: 0xC0000005: 读取位置 0xfdfdfdfd 时发生访问冲突
高手解释下,难道swscanf_s函数就不能用%s做格式符?
1. 其他数据类型都是T,而你这个函数却是W的,有可能不匹配,而stscanf显然就匹配了
2. str.GetBuffer是不正确的,你应该直接用str,GetBuffer只有当你需要LPTSTR时才需要,而这里需要的是LPCTSTR
_stprintf_s在MBCS为sprintf_s
在UNICODE下为swprintf_sCString的长度是自动增长的.这里用下面语句合适点吧.
str.Format(_T("%s%s"), szBuff, szBuff2);
CStringA -- sscanf
CString -- _stscanf
CStringW -- swscanf
你可以这样:
str.Format(_T("%s%s"), szBuff, szBuff2);
------------------------------------------
w - 对应宽字符版本(Unicode版本), 还有就是窄字符版本(Ascii版本)
T - 可以兼容两种版本,看是否定义_UNICODE宏
你细细看一下MSDN对这个函数描述。
Example:
// crt_sscanf_s.c
// This program uses sscanf_s to read data items
// from a string named tokenstring, then displays them.#include <stdio.h>
#include <stdlib.h>int main( void )
{
char tokenstring[] = "15 12 14...";
char s[81];
char c;
int i;
float fp; // Input various data from tokenstring:
// max 80 character string plus NULL terminator
sscanf_s( tokenstring, "%s", s, _countof(s) );
sscanf_s( tokenstring, "%c", &c, sizeof(char) );
sscanf_s( tokenstring, "%d", &i );
sscanf_s( tokenstring, "%f", &fp ); // Output the data read
printf_s( "String = %s\n", s );
printf_s( "Character = %c\n", c );
printf_s( "Integer: = %d\n", i );
printf_s( "Real: = %f\n", fp );
}
直到看完整个文档,看到这个实例,才发现原来还有猫腻!sscanf_s 取值的时候,需要在每个取值后面指定取值的最大大小。
最好buffer使用数组,因为Vs2008的CString 和VC的CString 机制已经发生了变化。
#include <stdlib.h>int _tmain()
{
TCHAR str[] = _T("CSFS dfdfd");
TCHAR szBuff[100] = {0};
TCHAR szBuff2[100] = {0};
_stscanf_s(str, _T("%s%s"), szBuff, _countof(szBuff), szBuff2, _countof(szBuff2));
_tprintf(_T("%s\n%s\n"), szBuff, szBuff2); return 0;
}