应该掌握的神奇函数——sscanf的用法
生活随笔
收集整理的這篇文章主要介紹了
应该掌握的神奇函数——sscanf的用法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
概述:
sscanf的作用:從一個字符串中讀進于指定格式相符的數據。利用它可以從字符串中取出整數、浮點數和字符串。
sscanf和scanf的區別:scanf是以鍵盤作為輸入源,sscanf是以字符串作為輸入源。
sscanf:
原型:
int sscanf(const char *str, const char *format,......);說明:
sscanf()會將參數str的字符串根據參數format字符串來轉換格式并格式化數據。轉換后的結果存于對應的參數內。
成功則返回參數數目,失敗則返回0。
舉例:
1、賦值
將第一個參數的值賦給第三個參數。
#include <iostream> using namespace std; int main() {char str[10];//功能1:賦值 for(int i = 0; i < 10; i++) str[i] = '!';sscanf("123456", "%s", str); cout << str << endl; return 0; }輸出:123456。
2、截取。%3s表示截取3位字符
#include <iostream> using namespace std; int main() {char str[10];for(int i = 0; i < 10; i++) str[i] = '!';sscanf("1234567", "%3s", str); cout << str << endl; return 0; }輸出:123。
3.1、取固定區間。%[a-z]表示只取a-z區間的數(注意一定是連續的)。
#include <iostream> using namespace std; int main() {char str[10];for(int i = 0; i < 10 ; i++) str[i] = '!';sscanf("aaaAAAqqq", "%[a-z]", str); cout << str << endl; return 0; }輸出:aaa。
3.2、同上,%[a-zA-Z]表示取a-z及A-Z區間的數(注意一定是連續的)。
#include <iostream> using namespace std; int main() {char str[10];for(int i = 0; i < 10 ; i++) str[i] = '!';sscanf("aaaAAAqqq", "%[a-zA-Z]", str); cout << str << endl; return 0; }輸出:aaaAAAqqq。
4.1:取指定字符為止的字符串。%[^+]表示取到+號為止的字符串
#include <iostream> using namespace std; int main() {char str[10];for(int i = 0 ; i < 10 ;i++) str[i] = '!'; sscanf("AAAaa+BBB", "%[^+]", str); cout << str << endl; return 0; }輸出:AAA。
4.2:同理,%[^ ]表示取到空格為止的字符串
#include <iostream> using namespace std; int main() {char str[10];for(int i = 0; i < 10; i++) str[i] = '!';sscanf("AAA BBB", "%[^ ]", str);cout << str << endl; return 0; }輸出:AAA。
4.3:第三條與第四條結合,%[^a-z ]表示取到a-z任意字符為止的字符串
#include <iostream> using namespace std; int main() {char str[10];for(int i = 0; i < 10; i++) str[i] = '!';sscanf("AAAaBBB", "%[^a-z]", str);cout << str << endl; return 0; }輸出:AAA。
5.1:跳過某種類型的數據不讀取。%*d%s表示跳過int型數據讀取字符串
#include <iostream> using namespace std; int main() {char str[10];for(int i = 0; i < 10; i++) str[i] = '!';sscanf("1234ABCD", "%*d%s", str);cout << str << endl; return 0; }輸出:ABCD。
5.2:與第三條結合,%[*a-z]%s表示跳過a-z字符讀取字符串
#include <iostream> using namespace std; int main() {char str[10];for(int i = 0; i < 10; i++) str[i] = '!';sscanf("aaaABCD", "%[*a-z]%s", str);cout << str << endl; return 0; }輸出:ABCD。
6、從字符串中第n個以后截取一個某類型數據。sscanf(&a[0], "%d", &v);表示從a[0]開始截取一個int型數據賦給v
#include <iostream> using namespace std; int main() {char a[10] = "11,22,33";int v;sscanf(&a[0], "%d", &v);cout << v << endl; return 0; }輸出:ABCD。
補充:
關于什么時候有& 什么時候不要& ?
和scanf一樣,scanf("%d",&a); 和scanf("%s",str); 取地址,str就是首地址,所以不加&。
擇苦而安,擇做而樂,虛擬現實終究比不過真實精彩之萬一。
總結
以上是生活随笔為你收集整理的应该掌握的神奇函数——sscanf的用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 12行代码AC——例题6-6 小球下落(
- 下一篇: 43行代码AC——例题6-8 树(Tre