[問題] 如何從string 中抓取數字來用?

看板C_and_CPP (C/C++)作者 (外星人)時間12年前 (2013/10/20 14:07), 編輯推噓3(305)
留言8則, 6人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 要如何從一個string中抓取數字使他成為整數來用? 餵入的資料(Input): "28/9/2005" 預期的正確結果(Expected Output): int x,y,z (希望可以把28,9,2005分別抓到x,y,z來用) 錯誤結果(Wrong Output): 我得程式碼只抓出一個28 程式碼(Code):(請善用置底文網頁, 記得排版) #include<stdio.h> #include<stdlib.h> #include<string> #include<iostream.h> #include<sstream> using namespace std; int main(){ string a = "28/9/2005"; char test[20]; strcpy(test,a.c_str()); char *endPtr = test; long int li1 , li2; li1 = strtol(test,&endPtr,0); li2 = strtol(test,&endPtr,0); printf("%ld,%ld",li1,li2); } 補充說明(Supplement): -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 111.248.145.26

10/20 14:47, , 1F
sscan(a, "%d/%d/%d", &li1, &li2, &li3);
10/20 14:47, 1F

10/20 14:47, , 2F
^sscanf
10/20 14:47, 2F

10/20 16:29, , 3F
超霸氣 iostream.h
10/20 16:29, 3F

10/20 16:36, , 4F
用regex
10/20 16:36, 4F

10/20 19:24, , 5F
你可以每次執行完stroul之後印一下test
10/20 19:24, 5F

10/20 19:24, , 6F
講錯 是印endptr
10/20 19:24, 6F

10/20 19:50, , 7F
stringstream
10/20 19:50, 7F

10/21 13:23, , 8F
都用std::string了 就甭用strtol/strtok了唄
10/21 13:23, 8F
文章代碼(AID): #1IOtC4Po (C_and_CPP)
文章代碼(AID): #1IOtC4Po (C_and_CPP)