2011-12-31 182 views
-3

當我嘗試這樣的:比較字符串文本

string msm_arg1; 

...

if (msm_arg1 = "--console") 
run_console(); 

我得到:

res/functions/ReadArgs.h|40|error: could not convert ‘msm_arg1.std::basic_string<_CharT, _Traits, _Alloc>::operator= [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>, std::basic_string<_CharT, _Traits, _Alloc> = std::basic_string<char>](((const char*)"-c"))’ from ‘std::basic_string<char>’ to ‘bool’| 

我所看到的是,它正試圖將一個字符串(msm_arg1)與一個bool進行比較,「--console」顯然不是。

我可以看到一個可能的解決方法:創建一個字符串進行比較,但是可能會有CLI參數,可能會變得混亂。

我在默認的gcc上使用Ubuntu 11:10上的Code :: Blocks。

+0

-1:基本參考問題。我敢肯定,你的C++書有一個關於操作符的章節。 – 2011-12-31 14:38:36

+0

@ TomalakGeret'kal:如果他有一本書,那就是。 :-) – 2011-12-31 15:12:52

+0

@SergioTulentsev:在訴諸免費求助之前,他必須絕對有一本書! – 2011-12-31 15:15:45

回答

5

=是賦值運算符。

目前,您的代碼做這個:

if (msm_arg1 = "--console") 
//  \____________________/ 
//  assign to msm_arg1; 
//  evaluate to new value 
// 
    if (msm_arg1) 
//  \______/ 
//  convert string to bool 
//  for `if` comparison 
// 
// ERROR: Can't do that! 

C++中等價算==

if (msm_arg1 == "--console") 

而且這是值得意識到,這是一個病例如果您停止使用std::string並嘗試比較兩個文字,它將無法正常工作。

+0

謝謝!我昨晚很晚,所以這可能是我爲什麼這麼做的原因! – NRoach44 2012-01-01 01:58:32

+0

@ NRoach44:Pas de probleme :) – 2012-01-01 02:21:47