使用sscanf从String中读取多个值

时间:2013-10-23 14:43:13

标签: c++ memory-leaks

我想从文件中读取数据行。我尝试的一切都行不通。

以下是数据的示例:

“< x = 128 y = 480 img = img / A.png type = passable>”

现在我想从这个字符串中读取4个值。

char img[256];
char ObjectType[256];
sscanf_s(lines[i].c_str(),"< x = %i y = %i img = %s type = %s >",&x,&y,img,ObjectType);

但每次我得到Memoryleaks。

你有什么想法吗?

编辑:

我用我的opionion不洁方法解决了我的问题。我用了一个istringstream:

            istringstream iss(lines[i]);
            iss >> temp >> temp >> temp >>
            x >> temp >> temp >>
            y >> temp >> temp >>
            img >> temp >> temp >> 
            ObjectType;

1 个答案:

答案 0 :(得分:1)

改为使用以下行:

sscanf_s(lines[i].c_str(),"< x = %i y = %i img = %s type = %s >",&x,&y,img, _countof(img),ObjectType,_countof(ObjectType));

来自msdn documentation of sscanf_s

  

使用type字段时需要缓冲区大小参数   字符c,C,s,S和[。缓冲区大小必须是字符   在需要的每个缓冲区之后作为附加参数提供   它

您缺少缓冲区大小参数,因此它尝试将未知数量的字节写入img,之后尝试将您要写入ObjectType的内容写入未定义的内存位置,因此您遇到的例外情况。