2013-05-11 33 views
2
#include <iostream> 
#include <string.h> 
using namespace std; 

int main() { 
char *tok; 
string s = "Ana and Maria are dancing."; 
tok = strtok(s.c_str(), " "); 
while(tok != NULL) { 
    cout << tok << " "; 
    tok = strtok(NULL, " "); 
} 
return 0; 
} 

而且我得到這個錯誤:錯誤嘗試使用「的strtok」的字符串

:9:29: error: invalid conversion from ‘const char*’ to ‘char*’ [-fpermissive] 
In file included from ceva.cc:2:0: 
348:14: error: initializing argument 1 of ‘char* strtok(char*, const char*)’ [-fpermissive]" 
+1

你應該考慮改變劇情,我的意思是安娜和瑪麗亞正在做什麼,或者這個問題會被標記爲冒犯性的。 – biggdman 2013-05-11 09:10:52

回答

4

strtok()在其解析破壞性(即它寫入給你,而你解析它解析字符串),所以它需要一個char*作爲參數,而不是一個const char*

c_str()返回一個const char*,因爲它不指望您寫入它返回的緩衝區的內容。

解析的一種方法是strdup()(即複製)你想要工作的緩衝區並解析它,即;

char* buf = strdup(s.c_str()); 
tok = strtok(buf, " "); 
... 

請記住,一旦你完成了它,即可釋放副本。

2

的問題是,c_str()返回const char*,因爲string對象應該是主人緩衝區的封裝字符串的存儲位置,所以您無權修改它,除非通過string的成員函數。

在另一方面,strtok()接受一個指向(非constchar,即char*,這是編譯器抱怨什麼:你想傳遞的東西不可修改到想要修改的功能那個東西。

如果我可以提出一個更好的辦法,這是在C++ 11更地道,因爲你正在使用std::string無論如何,而做到以下幾點:

#include <iostream> 
#include <string> 

int main() 
{ 
    std::string s = "Ana and Maria are dancing"; 

    std::string::size_type start = 0; 
    std::string::size_type pos = s.find(" "); 
    while (pos != std::string::npos) 
    { 
     std::string tok = s.substr(start, pos - start); 
     std::cout << tok << " "; 

     start = pos + 1; 
     pos = s.find(" ", start); 
    } 
} 

上面的代碼也移除了這個指令:

using namespace std; 

它通常被認爲是不好的編程習慣(特別是當放在全局命名空間範圍內時),因爲它很容易導致名稱與屬於std命名空間的實體發生衝突。

+0

感謝您的選擇;我通過加入 char * d = strdup(s.c_str())來解決它。 tok = strtok(d,「」); – 2013-05-11 09:25:24

+0

@MardaloescuSerban:好的,很高興你管理 – 2013-05-11 09:26:16

相關問題