[問題] C++ string 與 C char* 使用strtok的問題

看板C_and_CPP (C/C++)作者 (=.=)時間16年前 (2010/03/02 21:13), 編輯推噓0(006)
留言6則, 2人參與, 最新討論串1/3 (看更多)
遇到的問題: (題意請描述清楚) 1. 若用第9行代替第10行, 第14行的strtok會segmentation fault 2. 第18行的strtok()回傳NULL時,轉型為string的動作會產生 run time error error msg: terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_S_construct NULL not valid Aborted 開發平台: (例: VC++ or gcc/g++ or Dev-C++, Windows or Linux) Linux / g++ 有問題的code: (請善用置底文標色功能) 1 #include <iostream> 2 #include <map> 3 #include <string> 4 5 using namespace std; 6 7 int main() { 8 map<string, int> wordCtr; 9 // char* str = "this is a string this is another string"; 10 char str[] = "this is a string this is another string"; 11 char* sep = " "; 12 string word = ""; 13 14 word = (string)strtok(str, sep); 15 while (!word.empty()) { 16 cout << word << endl; 17 wordCtr[word]++; 18 word = (string)strtok(NULL, sep);// run time error when 19 // strtok returns NULL 20 } 21 22 return 0; 23 } 補充說明: 1. 請問 line 9 和 lin 10的寫法為什麼會對第14行的 strtok產生不同的效果? 2. 當strtok回傳NULL時該怎麼assign給word呢? 我知道可以用if else 先判斷strtok的回傳值再決定要assign什麼給word 但這種寫法似乎 "比較髒",總覺得應該有漂亮一點的寫法 不知道各位是怎麼做的呢? 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 68.232.127.230

03/02 21:16, , 1F
c++的string是一個物件喔
03/02 21:16, 1F

03/02 21:17, , 2F
既非字元陣列也不是字元指標 它就是一個物件
03/02 21:17, 2F

03/02 21:17, , 3F
因為 strtok 會修改 str 的內容 但 char * 是唯讀的
03/02 21:17, 3F

03/02 21:17, , 4F
所以 strtok 遇上 char * 就會錯誤
03/02 21:17, 4F

03/02 21:20, , 5F
2. 你可以用 try 與 catch 來解決那個 exception
03/02 21:20, 5F

03/02 21:20, , 6F
不過其實不會比較好...XD
03/02 21:20, 6F
文章代碼(AID): #1BZGy0OK (C_and_CPP)
文章代碼(AID): #1BZGy0OK (C_and_CPP)