string-parsing-cpp

I have always thought that CPP has a weaker string parsing API than JAVA. Recently I found a powerful function sscanf() in CPP which can be quite handy for parsing string with certain formats. Formatted standard input can also be handeled using similar scanf() function. The key feature of this/these function is that it provides a format matching which is quite similar to regex but easier to use - just using the format %[] and put the wanted characters in the bracket. Here is an example for using this:

1
2
3
4
5
6
7
8
9
10
11
#include<bits/stdc++.h>
using namespace std;

string test = "alice,12,34,seattle";
char name[50],city[50];
int cnt1,cnt2;
int main() {
sscanf(test.c_str(),"%[^,],%d,%d,%[^,]",name,&cnt1,&cnt2,city);
printf("%s\n%d\n%d\n%s\n",name,cnt1,cnt2,city);
return 0;
}

The above example uses %[^,] to match characters not equal to ‘,’. The output should be alice, 12, 34, seattle each with a single line.

Similarly, one can use %[a-z] to match any lower letter english characters. For more usage,please refer to: http://www.cplusplus.com/reference/cstdio/scanf/