前提・実現したいこと
ダブルクオーテーションを含む文字列をパースした後、文字列の配列に文字を格納するコードの作成
例:
cmd = "aaa bbb " ccc \t\n ddd eee " "をパース後
args[0] = "aaa", parsedlist[1] = "bbb", parsedlist[2] = " ccc \t\n ddd eee "となるようにしたい
試したこと
cmdを一文字ずつ見ていき"が発見されるまではスペースで文字を区切り
"が発見された後は終端の"が発見されるまで"区切り、という感じで実装してみたのですが
17行目でseg fault 11 でエラー終了します
C
1#include <stdio.h> 2#include <string.h> 3 4int main(){ 5 6 char* cmd = "hello world \" and hello universe \" "; 7 char args[10][100]; 8 char* check; 9 char p; 10 int quotationFound = 0; 11 12 int i=0; 13 int j=0; 14 for(; cmd[i]!='\0'; ++i){ 15 p = cmd[i]; 16 if(p=='\"') !quotationFound; 17 args[i][j++] = p;//seg fault 18 if(p==' ' && !quotationFound){ i++; j=0; } 19 } 20 21 return 0; 22} 23
コメントを受けて訂正した所無事動かすことができましたm(_ _)m
修正後コード
C
1#include <stdio.h> 2#include <string.h> 3 4int main(){ 5 6 char* cmd = "hello world \" and hello universe \" "; 7 char args[10][100]; 8 char* check; 9 char p; 10 int quotationFound = 0; 11 12 int i=0; 13 int j=0; 14 int k=0; 15 for(; cmd[i]!='\0'; i++){ 16 p = cmd[i]; 17 if(p=='\"') 18 quotationFound = !quotationFound; 19 20 args[k][j++] = p; 21 22 printf("p is now : %c\n", p); 23 24 if(p==' ' && !quotationFound){ 25 k++; j=0; 26 } 27 } 28 29 printf("args[0] : %s\n", args[0]); 30 printf("args[1] : %s\n", args[1]); 31 printf("args[2] : %s\n", args[2]); 32 printf("args[3] : %s\n", args[3]); 33 34 return 0; 35} 36
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/04/25 00:21
2018/04/25 00:34
2018/04/25 00:39