Re: [問題] sscanf
看板C_and_CPP (C/C++)作者LPH66 ((short)(-15074))時間16年前 (2009/06/21 00:58)推噓4(4推 0噓 1→)留言5則, 5人參與討論串3/3 (看更多)
※ 引述《elfkiller (沒有暱稱)》之銘言:
: #include<stdio.h>
: #include<string.h>
: #include<stdlib.h>
: int main(){
: char *p="ya yo hi";
: char pp[100];
: printf("%d\n",sscanf(p,"%*s%s%s",pp));
: //sscanf(p,"%s%s",pp);
: puts(pp);
: getchar();
: //system("pause");
: return 0;
: }
: 預期結果為:
: 2
: yohi
: _
: 可是卻會發生執行錯誤
: 編譯可過
: 不知問題是出於何處呢?
: dev c++ in XP
問題在於
你期望 sscanf 他幫你把中間內含一組空白的字串讀進 pp
但 sscanf 根本不會知道你想要的是這樣
(不然哪天你發瘋了想混搭
前三個進 pp 再來兩個進 qq 再來四個進 rr 等等 這樣 sscanf 怎麼辦? XD)
所以還是乖乖的讀進兩個字串裡去吧:
char *p="ya yo hi";
char pp[100],qq[100];
printf("%d\n",sscanf(p,"%*s%s%s",pp,qq));
printf("%s%s\n",pp,qq);
另外回一個推文
: → iamivers0n:參數少兩個 06/20 22:27
其實只少一個
%*s 用在 -scanf 系的函式的意義為讀進字串後丟掉
所以第一個讀進去的 (此例中為 ya) 就會被跳過去
(同理, %*d 即為跳過一個整數)
而 %*s %*d 之類的用在 -printf 系的函式上的意義是
寬度值由接下來的參數 (需要是個整數) 表示
因此 printf("%*s",10,string); 和 printf("%10s",string); 是一樣的意思
差別在於 這個 10 的位置既然是在參數列而不是字串中 那自然也能用變數
所以可以寫 printf("%*s",width,string); 來動態指定寬度
--
'Oh, Harry, dont't you see?' Hermione breathed. 'If she could have done
one thing to make absolutely sure that every single person in this school
will read your interview, it was banning it!'
---'Harry Potter and the order of the phoenix', P513
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.112.30.84
推
06/21 01:18, , 1F
06/21 01:18, 1F
推
06/21 01:45, , 2F
06/21 01:45, 2F
推
06/21 02:15, , 3F
06/21 02:15, 3F
推
06/21 02:32, , 4F
06/21 02:32, 4F
→
06/21 12:14, , 5F
06/21 12:14, 5F
討論串 (同標題文章)
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章