|
| 1 | +#include <cstdio> |
| 2 | +#include <iostream> |
| 3 | +#include <string> |
| 4 | + |
| 5 | +using namespace std; |
| 6 | + |
| 7 | +// https://stackoverflow.com/questions/41692561/parsing-a-string-with-scanf |
| 8 | +// https://stackoverflow.com/questions/8141208/sscanf-with-delimiter-in-c |
| 9 | +// https://edisonx.pixnet.net/blog/post/75487541 |
| 10 | + |
| 11 | +int main(void) { |
| 12 | + float x = 0.0f, y = 0.0f; |
| 13 | + char name[30], date[30], suffix[30]; |
| 14 | + |
| 15 | + name[0] = date[0] = suffix[0] = '\0'; |
| 16 | + |
| 17 | + // if delimeter is ' ' |
| 18 | + string my_string = "myname 20220330-153848 x0.20 y0.00 mysuffix.txt"; |
| 19 | + sscanf(my_string.c_str(), "%s %s x%f y%f %s", name, date, &x, &y, suffix); |
| 20 | + cout << name << ", " << date << ", " << x << ", " << y << ", " << suffix |
| 21 | + << endl; |
| 22 | + |
| 23 | + x = 0.0f, y = 0.0f; |
| 24 | + name[0] = date[0] = suffix[0] = '\0'; |
| 25 | + |
| 26 | + // if delimeter is '_' |
| 27 | + my_string = "myname_20220330-153848_x0.20_y0.00_mysuffix.txt"; |
| 28 | + sscanf(my_string.c_str(), "%[^_]_%[^_]_x%f_y%f_%s", name, date, &x, &y, |
| 29 | + suffix); |
| 30 | + cout << name << ", " << date << ", " << x << ", " << y << ", " << suffix |
| 31 | + << endl; |
| 32 | + return 0; |
| 33 | +} |
| 34 | + |
| 35 | +/* |
| 36 | +myname, 20220330-153848, 0.2, 0, mysuffix.txt |
| 37 | +myname, 20220330-153848, 0.2, 0, mysuffix.txt |
| 38 | +*/ |
0 commit comments