sscanf_s无法从字符串中找到所有值

时间:2016-10-11 05:33:27

标签: c++ string visual-c++ format scanf

我想从一串文本中解析整数:

"f 1/2/3 4/5/6 7/8/9"

成:

int arr1[3] = { 1, 4, 7 };
int arr2[3] = { 2, 5, 8 };
int arr3[3] = { 3, 6, 9 };

我编写了以下代码,根据字符串的一般格式使用sscanf_s进行解析:

// line = "f 1/2/3 4/5/6 7/8/9"
int arr1[3], arr2[3], arr3[3];

sscanf_s(line.c_str(), "f %d/%d/%d %d/%d/%d %d/%d/%d",
    &arr1[0], &arr2[0], &arr3[0],
    &arr1[1], &arr2[1], &arr3[1],
    &arr1[2], &arr2[2], &arr3[2]);

奇怪的是,运行此代码后我的数组内容是:

arr1 = { 4, 7, -858993460 };
arr2 = { 5, 8, -858993460 };
arr3 = { 6, 9, -858993460 };

这是一种奇怪的结果,它几乎就像正确地加载数据但是然后将数组向左移动一个。奇怪的是,sscanf_s返回9,表示它使用我传入的格式找到了9个匹配。我一直在尝试查找错误,但我真的看不出代码出错了。< / p>

1 个答案:

答案 0 :(得分:0)

刚刚编译了这段代码:

#include <iostream>
#include <cstdio>

using namespace std;

int arr1[3], arr2[3], arr3[3];

int main()
{
    std::string line = "f 1/2/3 4/5/6 7/8/9";
    sscanf_s(line.c_str(), "f %d/%d/%d %d/%d/%d %d/%d/%d",
        &arr1[0], &arr2[0], &arr3[0],
        &arr1[1], &arr2[1], &arr3[1],
        &arr1[2], &arr2[2], &arr3[2]);

    std::cout << "arr1 : " << arr1[0] << ", " << arr1[1] << ", " << arr1[2] << std::endl;
    std::cout << "arr2 : " << arr2[0] << ", " << arr2[1] << ", " << arr2[2] << std::endl;
    std::cout << "arr3 : " << arr3[0] << ", " << arr3[1] << ", " << arr3[2] << std::endl;
}

它运作正常。