• C++ Help: Strings
    7 replies, posted
I got this code here: [php]gLua->Msg( gLua->GetString(1) << " is a faggot.\n");[/php] [code] 1>.\main.cpp(12) : error C2296: '<<' : illegal, left operand has type 'const char *' 1>.\main.cpp(12) : error C2297: '<<' : illegal, right operand has type 'const char [15]' [/code] I have no idea how to do that, like in lua it's " .. " . So FP, how'dyou do it? :byodood:
[b]THIS IS WRONG IN YOUR CASE, LOOK AT THE POST BELOW ME[/b] string+string So your code would be: [cpp]gLua->Msg( gLua->GetString(1) + " is a faggot.\n"); [/cpp] And what you were looking for is called string concatenation. -- To address what you [i]did[/i] write, the << operator is stream output, and only works with streams. You probably thought it did concatenation because it will function similarly when used with a cout (io[b]stream[/b]). You [i]will[/i] have to use it if you wish to concatenate something that isn't a string, for example, to insert a variable into a string, in which case in many cases it is advantageous to use a stringstream, like so: [cpp] int VarA = 17; std::string FinalString; std::stringstream Stream; Stream << "Variable VarA is currently: " << VarA; FinalString = Stream.str(); //convert to a std::string [/cpp]
From the error message, it sounds like gLua->GetString(1) is returning a const char*, not a std::string. String concatentation doesn't work on those. Try this instead: [code] gLua->Msg( std::string(gLua->GetString(1)) + " is a faggot.\n"); [/code]
1>.\main.cpp(11) : error C2110: '+' : cannot add two pointers :black101:
[QUOTE=Wyzard;20864380]From the error message, it sounds like gLua->GetString(1) is returning a const char*, not a std::string. String concatentation doesn't work on those.[/QUOTE] Ah, good catch, I sprung immediately to the incorrect concatenation operator and forgot to read the error message.
Wyzard with your one i get this: 1>.\main.cpp(11) : error C2039: 'string' : is not a member of 'std' 1>.\main.cpp(11) : error C3861: 'string': identifier not found [editline]01:58AM[/editline] I did #include <string> and now I get this 1>.\main.cpp(11) : error C2664: 'ILuaInterface002::Msg' : cannot convert parameter 1 from 'std::basic_string<_Elem,_Traits,_Ax>' to 'const char *' 1> with 1> [ 1> _Elem=char, 1> _Traits=std::char_traits<char>, 1> _Ax=std::allocator<char> 1> ] 1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
Oops, I forgot that part. Wrap the string concatentation in parentheses and call .c_str() on the result. (Adding two strings gives you another string, and calling c_str() on that string gives you the char* that gLua-Msg() needs.) [code] gLua->Msg((std::string(gLua->GetString(1)) + " is a faggot.\n").c_str()); [/code]
The best way, without using std::strings or stuff. [code]gLua->Msg("%s is a faggot.\n", gLua->GetString(1));[/code]
Sorry, you need to Log In to post a reply to this thread.