看板 C_and_CPP 關於我們 聯絡資訊
開發平台(Platform): (Ex: Win10, Linux, ...) OS X 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) 編譯器:xcode8 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 各位先進好,我是c++新手,在寫一個將ip逐行分開的程式,(1|2|3|4=>1 2 3 4) 現在我遇到的問題是我getline讀到的string沒辦法丟給strtok去處理 餵入的資料(Input): 餵入資料:寫入TXT檔案 預期的正確結果(Expected Output): 預期出現分割string 錯誤結果(Wrong Output): 錯誤結果:Token: line.str() 程式碼(Code):(請善用置底文網頁, 記得排版) int main () { string line; ifstream myfile ("myfile.txt"); if (myfile.is_open()) { while ( getline (myfile,line,'\n') ) { char *p = strtok("line.c_str()", "|"); while (p) { printf ("Token: %s\n", p); p = strtok(NULL, "|"); } cout << line << '\n'; } myfile.close(); } else cout << "Unable to open file"; return 0; *[36m補充說明(Supplement):*[m -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 150.135.210.46 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1478378813.A.4B7.html
EdisonX: 1. strtok(line.c_str(), "|") ; ---> 注意還是會有問題 11/06 04:50
※ 編輯: acgotaku (150.135.210.46), 11/06/2016 04:51:50
EdisonX: 2. 因 strtok 會改變字串內容, 而 line.c_str() 傳回的是 11/06 04:51
EdisonX: const char * , 意指不想讓你改變, 所以建議先做一份副本 11/06 04:51
EdisonX: (用 strcpy) ,再做 strtok. 11/06 04:52
steve1012: 我會想用find_first_of 自己parse 11/06 04:57