C++字符串函数补充 #
之前我们学习了c++中的字符串,也就是char数组,现在我们补充两个非常实用的函数,sscanf和sprintf,这两个字符串函数可以方便地实现数字和字符串之间的转化:
sprintf(s, “%d”, N) #
函数说明:将数字 N 转化成字符串 s。
请看例程:
#include < iostream >
#include < string >
#include <stdio.h>
using namespace std;
int main()
{
char dashima[3];//可以写更大的数字例如:dashima[10]
int n = 125;
sprintf(dashima,"%d",n);
printf("%s", dashima);
return 0;
}
注意,sprintf 本身是用于字符串的格式化的。它的使用方式和 printf 相类似。
请看例程:
#include < iostream >
#include < string >
#include <stdio.h>
using namespace std;
int main()
{
char dashima[100];
int n = 125;
sprintf(dashima, "Eg-1, Time: %d:%d.", 12, 30);
printf("%s\n",dashima);
printf("Eg-2, Time: %d:%d.\n", 12, 30);
return 0;
}
sscanf(s, “%d”, &N) #
函数说明:将字符串 s 转化成数字 N。
请看例程:
#include < iostream >
#include < string >
using namespace std;
int main()
{
string a = "29";
int n = 0;
sscanf(a.c_str(), "%d", &n); // 注意引用符号
cout << n << endl;
return 0;
}
注意,sscanf 本身是用于字符串内容解析。它的使用方式和 scanf 相类似。
请看例程:
#include < iostream >
#include < string >
using namespace std;
int main()
{
string str = "12:30";
int a, b;
sscanf(str.c_str(), "%d:%d", &a, &b);
return 0;
}
C++字符串 & String 实战演练 #
接下来,尝试使用前几节课学习的字符串和String的知识解决下面的问题吧: