最近在项目中发现了sscanf函数,你这个函数咋就这么牛逼呢?
看看,如何分割字符串:
#include <iostream>
using namespace std;
int main()
{
char str[100] = " id = 123456 "; // 注意:等号两边必须留空字符
char str1[20] = {0};
char str2[20] = {0};
sscanf(str, "%s = %s", str1, str2); // 注意:等号两边必须留空字符;str1为"id", str2为"123456"
return 0;
}
继续看下面的程序:
#include <iostream>
using namespace std;
int main()
{
char buf[512] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" ;
sscanf("123456 ", "%4s", buf); // buf为"1234"
return 0;
}
#include <iostream>
using namespace std;
int main()
{
char buf[100] = {0};
sscanf("123456 abcdedf", "%[^ ]", buf); // buf为"123456"
return 0;
}
#include <iostream>
using namespace std;
int main()
{
char buf[100] = {0};
sscanf("123456 xyz *** abcdedf", "%[^*]", buf); // buf为"123456 xyz "
return 0;
}
#include <iostream>
using namespace std;
int main()
{
char buf[100] = {0};
sscanf("123456abcdedfBCDEFabc", "%[1-9a-z]", buf); // buf为"123456abcdedf"
return 0;
}
好了,我也不想穷尽sscanf的用法,不可能也没有必要。要用的时候,要记得想起,想起那个有用的sscanf, 然后快速查阅sscanf的功能,并找到你需要的信息,快速解决问题。