[問題] strtok與getline同時使用

作者: acgotaku (otaku)   2016-11-06 04:46:50
開發平台(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
作者: EdisonX (卡卡獸)   2016-11-06 04:50:00
1. strtok(line.c_str(), "|") ; ---> 注意還是會有問題2. 因 strtok 會改變字串內容, 而 line.c_str() 傳回的是const char * , 意指不想讓你改變, 所以建議先做一份副本(用 strcpy) ,再做 strtok.
作者: steve1012 (steve)   2016-11-06 04:57:00
我會想用find_first_of 自己parse

Links booklink

Contact Us: admin [ a t ] ucptt.com