I want to parse integers from a string of text that looks like:
"f 1/2/3 4/5/6 7/8/9"
into:
int arr1[3] = { 1, 4, 7 };
int arr2[3] = { 2, 5, 8 };
int arr3[3] = { 3, 6, 9 };
I wrote the following code to use sscanf_s
to parse according to the general format of the strings:
// 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]);
Strangely, the contents of my arrays after running this code are:
arr1 = { 4, 7, -858993460 };
arr2 = { 5, 8, -858993460 };
arr3 = { 6, 9, -858993460 };
This is a kind of strange result, it's almost like it loads in the data correctly but then shifts the arrays to the left by one. Strangely, sscanf_s
returns 9
, which indicates that it found 9 matches using the format I passed in. I have been trying to find an error but I really do not see what the code is doing wrong.
Just compiled this code:
#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;
}
And it works fine.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.