利用标准库sprintf、sscanf函数实现字符串和数字的转换
生活随笔
收集整理的這篇文章主要介紹了
利用标准库sprintf、sscanf函数实现字符串和数字的转换
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、sprintf() 用于將數字轉化為字符串
1、將整數轉化為字符串
#include<iostream>
using namespace std;int main()
{char str[10];int a = 121;//將整數轉化為字符串//strlen(char*)函數求的是字符串的實際長度sprintf(str, "%d", a);int len = strlen(str);cout << "字符串:" << str << endl;cout << "長度:" << len << endl;system("pause");return 0;
}
2、將浮點數轉化為字符串
注意:%lf:其中,l表述輸出double類型,f代表輸出的是浮點數。
#include<iostream>
using namespace std;int main()
{char str[10];double a = 121.2;//將浮點數轉化為字符串//strlen(char*)函數求的是字符串的實際長度sprintf(str, "%.1lf", a);int len = strlen(str);cout << "字符串:" << str << endl;cout << "長度:" << len << endl;system("pause");return 0;
}
二、sscanf() 用于將字符串轉化為數字
1、將字符串轉化為整數
#include<iostream>
using namespace std;int main()
{char str[]="121";int a ;//將字符串轉化為整數//strlen(char*)函數求的是字符串的實際長度sscanf(str, "%d", &a);cout << "整數:" << a << endl;system("pause");return 0;
}
2、將字符串轉化為浮點數
注意:%lf:其中,l表述輸出double類型,f代表輸出的是浮點數。
#include<iostream>
using namespace std;int main()
{char str[]="121.2";double a ;//將字符串轉化為浮點數//strlen(char*)函數求的是字符串的實際長度sscanf(str, "%lf", &a);cout << "浮點數:" << a << endl;system("pause");return 0;
}
總結
以上是生活随笔為你收集整理的利用标准库sprintf、sscanf函数实现字符串和数字的转换的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (C++)类内运算符重载时:此运算符函数
- 下一篇: 回文数:给你一个整数 x ,如果 x 是