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做格式符?

解决方案 »

  1.   

    很多问题:
    1. 其他数据类型都是T,而你这个函数却是W的,有可能不匹配,而stscanf显然就匹配了
    2. str.GetBuffer是不正确的,你应该直接用str,GetBuffer只有当你需要LPTSTR时才需要,而这里需要的是LPCTSTR
      

  2.   

    不知道你的工程用的是MBCS还是UNICODE,如果是前者后面函数肯定会出问题,根据你写的推测应该用的是MBCS,
    _stprintf_s在MBCS为sprintf_s
    在UNICODE下为swprintf_sCString的长度是自动增长的.这里用下面语句合适点吧.
    str.Format(_T("%s%s"), szBuff, szBuff2);
      

  3.   

    你的工程是MBCS的,你用w的函数版本当然就不对了。弄清楚ansi,t,unicode的区别,必须保持一致。你用用_T("")的话,处理字符串的函数也要用_T的,如果你是CStringW,再用swscanf_s
    CStringA   --   sscanf
    CString    --  _stscanf
    CStringW   --   swscanf
      

  4.   

    工程应该是UNICODE的,不然swscanf_s(str.GetBuffer(), _T("%s%s"), szBuff, szBuff2);这句编译不过去.主要问题在str.GetBuffer()这个最好只用来访问,而不要用来修改数据,
    你可以这样:
    str.Format(_T("%s%s"), szBuff, szBuff2);
      

  5.   

    1. 其他数据类型都是T,而你这个函数却是W的,有可能不匹配,而stscanf显然就匹配了
    ------------------------------------------
    w - 对应宽字符版本(Unicode版本), 还有就是窄字符版本(Ascii版本)
    T - 可以兼容两种版本,看是否定义_UNICODE宏
      

  6.   

    VS2008写程序时用到这个函数的安全版本 sscanf_s ,实惠出现异常问题。
    你细细看一下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 机制已经发生了变化。
      

  7.   

    所以和什么unicode之类的都没关系了。VC2008的函数已经和VC6有很大的区别,所以在使用之前都要看一下MSDN比较好。
      

  8.   

    #include "stdafx.h"#include <stdio.h>
    #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;
    }