sscanf_s,双倍%c

-2 c++ scanf

当我想提取两个字符时,我遇到了sscanf_s的一些问题.

示例代码:

#include "stdafx.h"
#include <iostream>
#include <string.h>

int _tmain(int argc, _TCHAR* argv[])
{
   char* text = "ab";
   char a = ' ';
   char b = ' ';

   sscanf_s(text, "%c%c", &a, &b); //the same problem when I use %1c%1c

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我运行它时,这不起作用:

ConsoleApplication2.exe中0x0F76D6AC(msvcr120d.dll)的未处理异常:0xC0000005:访问冲突写入位置0x00000000.

当我尝试使用两个整数时%i%i,一切都正常.

ame*_*yCU 5

您需要指定大小.

[...]除了使用%c,%s%[转换说明每个期望两个参数(通常的指针和类型rsize_t的指示的接收阵列,的大小的值与%C读入一个单个字符时可以是1.

供参考 - http://en.cppreference.com/w/c/io/fscanf

因此,使用1大小来读取单个char

像这样重写 -

sscanf_s(text, "%c%c", &a,(rsize_t)1,&b,(rsize_t)1);
  //explicit casts as corrected in comments by chux
Run Code Online (Sandbox Code Playgroud)