I'm working on a little console game with ncurses. In the main menu I want the user to be able to set the control keys. Now as far as I understood, in ncurses you can access e.a. the a-key by the int value of the char 'a'. Using the key ingame with 'a' works flawlessly, however I'm stuck with the menu:
For each key binding I have stored an int-value that is defaulted to e.a. 'a'. When the game starts, I read the 'a' binding correctly from the int-value and can use it ingame. However, it is not displayed correctly. I want it to be like this: "Left: a". I do it like this:
std::string key = "Left: " + static_cast<char>(_value);
_value being the int-value I stored and initialized as 'a'. I also tried it without the cast, btw.
Now what's being displayed is strange. Instead of "a" it says "~T^C". For the letters "s" and "d" it doesn't display anything at all. "w" becomes some very strange encoding question marks.
I suppose it's got something to do with the encoding of the characters in int-values or something. So what can I do to get it displayed the right way?
Thanks a lot!
You're adding together the adress of string literal and ASCII value of _value. String key is then constructed from whatever happens to be at that garbage adress.
Remember that string literals are of type array of N const char and that arrays decay to pointer to their first element when passed to functions and operators etc., which yields you const char*. The built in + operator for pointers doesn't do string concatenation. You need to construct a std::string from at least one of operands for overloaded operator to kick in:
std::string key = std::string("Left: ") + static_cast<char>(_value);
Related
I'm trying to make a function which performs some operations on strings. From my understanding, strings are character arrays. So by writing:
cout << name[0];
we print the first character written of an assumed string called 'name'.
In my function, I have to use pointers to perform all functions. My current approach is to make a pointer:
string *str=&name;
but when I try to print the character at specified index by writing:
cout << *str[0];
It doesn't compile, I'm not sure what is the problem. One solution would be to make a dynamic character array but I wanted to know if it is possible to get the character at certain indexes of strings using pointers?
operator[] has higher precedence than operator*, so *str[0] is same as *(str[0]). str[0] returns a std::string, and calling operator* on std::string doesn't make sense.
Change it to (*str)[0].
I'm trying to convert the address of a pointer to a wxString of the wxWidgets library.
I have this book that presents a console based example to explain the input/output stream system in C++. Here we can print the address of some pointers without much complications using
const char *const variable = "again";
cout << static_cast<void*>(variable);
So far I can understand the example but (Now the complication)I want to make some GUI off the examples to train myself and explore the wxWidgets classes along with the book. I've successfully made some conversions with the As() method of the wxAny class and even compiled it without warnings or errors. But in execution time I get an "Assert failure" when trying to convert the types.
If I let the program continue it prints in my wxTextCtrl things like:
ﻌњ̎X(
Any ideas??
(btw I use CodeBlocks with Mingw32 and wxWidgets 3.0 in a windows 7 system)
this is the code that gives me the assert failure:
void ConsoleFrame::OnbtnFrase2Click(wxCommandEvent& event)
{
string chaine2("Value of the pointer: ");
void* puntero = &chaine2;
wxAny anyThing= puntero;
consoleText->AppendText(anyThing.As<wxString>());
}
This is the method that gives me the assert failure error.
Thanks to #Grady for correcting the code before.
Seems that I cannot convert a void* to a wxString. I have a gist of what may the problem be but, I cannot find a solution to the original problem of printing the address of a pointer in a text control (NOT the console screen)
A common way to do what you want in C++ is using std::stringstream (you need to #include <sstream>). The body of your function would then look like this:
string chaine2("Value of the pointer: ");
void* puntero = &chaine2;
stringstream tmpss;
tmpss << chaine2 << puntero;
consoleText->AppendText(tmpss.str());
If you just want to get a wxString containing everything that was output to that stream, you just do something like:
wxString mystr = tmpss.str();
I don't know what your question has to do with wxWidgets, but this works for me:
const char * dog = "dog";
std::cout << &dog;
I am no C++ expert.. but to me that looks like "output address of variable dog"
and if you want that as a string you could use a C++ string stream or just happy old C sprintf
char * addrString = (char *)malloc(sizeof(void *) * 2 + 3); // *2 bytes for hex rep, +3 for "0x" and null
sprintf(addrString, "%p",dog);
There is a difference between the address of a pointer and the contents of the pointer, especially with C-style (nul terminated sequence of characters).
For example:
const char * const text = "Some Text\n";
The variable text is a pointer to a string literal. The contents of the pointer is the location where the string literal resides; often called an address.
The expression, &text, represents the location or the address of the pointer. So if the pointer is residing at address 0x4000, the expression &text would return 0x4000; not the content of the pointer.
There are examples on StackOverflow for printing the address of a variable and the contents or the C-Style string.
So, do you want a wxString containing the address of a pointer or the string literal that the pointer points to?
At last!!
The answer to my question was here:
http://docs.wxwidgets.org/trunk/classwx_text_ctrl.html
This is the documentation of the text control. I just had to REDIRECT the output stream to the text control with:
wxStreamToTextRedirector redirect(myTextControl);
And now I use the cout object normally,
cout<<puntero;
and the output will be presented in the text control instead of a console screen. I could not create the wxString containing the address but so far this can at least show it. I know that from here on I can create a string from the contents of the text control and the member functions of it. If any of you guys have a better answer, I will gladly accep it. It is funny how the chapter of the book where I am is in/out streams and the solution to my problem is not presented in the book.
OK, I'm trying to work on a monolith of a program, and I've got a decent amount of the errors sorted through. The one's that's mystifying me right now is when I got "invalid conversion from 'char' to 'const char'" for this line:
sequenceMutation.insert( initialPosition, 'T' );
initialPosition itself is meant to be equal to sequenceIleChains[0] + 3, which corresponds to the index of the last character for the first Isoleucine group (plus one to account for the behavior of insert). I don't know why it would be outputting this, considering I initialize and declare string sequenceMutation locally in the function without const, so if anyone can figure this out, it would be useful.
Additionally, if it may help, I used
string sequenceMutation = sequenceOld[sequence];
to initialize and declare sequenceMutation, where sequenceOld is a vector that I pass by reference using vector<string>& sequenceOld and sequence is a integer value I initialize, declare, pass from the for loop in int main() that I'm putting this function within.
Replace the ' by ", you are inserting a string, not a char, see http://www.cplusplus.com/reference/string/string/insert/
I'm messing around with an Arduino board for the first time.
I have an array declared like this (I know don't judge me), it's for storing each character of the LCD as a sort of cache:
char* lcd_characters[] = {"","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""};
Then later on I'm trying to write to a specific slot of the array, like this, to save that letter to it:
new_char = String(message.charAt(i));
...blah blah blah...
lcd_characters[pos] = new_char; << error here
However it is giving me this error:
error: cannot convert 'String' to 'char*' in assignment
The funny thing is when I do this (below) it do assign the letter to it, however I have a var which is a single letter but can't assign it.
lcd_characters[pos] = "H";
Can someone help me out please. Thanks. I'm brand new to C and been ok so far.
Basically I want an array of characters and then I want to write on the array positions with a new value.
Why does it even matter what type of string I'm writing to that array position, I should be able to write a number or boolean there too and call it later. Is there something wrong with the way the array is declared initially?
Edit:
I tried...
lcd_characters[pos] = new_char.c_str();
however that's giving me the similar error:
invalid conversion from 'const char*' to 'char'
Wtf? All I want to do is say this array position equals this new value. That's it. I've done this a million times in javascript, ruby, python (even php) etc. I just want to go, this array... x[12] equals my letter in new_char !!!! Ahh.
A few remarks:
Are you using C or C++? String is a C++ class, but you are creating a an array of c strings (char *).
You are creating an array of strings (char* var[] equals to char**), but your naming suggests you want an array of characters. A c string is basically an array of characters, so stick with that (char * or char []).
I would recommend you go for only C code in this case:
char lcdChars[4] = {' ', ' ', ' ', ' '}; // init with spaces
lcdChars[2] = 'x'; // write x to position 3
Note: A string in C++ can output a C string (char *) by calling stringInstance.c_str().
I'm using OLEDB to connect to my local Oracle 11gR2 database in VC++. I'm using CCommand::Open to Select rows from my database, which should contain strings.
When I'm using GetValue to get my data though, I only get the first character.
Here are my attempts at getting that data. Note that the same behavior happens in "GetValue" and in "GetColumnName".
char* test = (CHAR*)cmd.GetColumnName(2);
cout << (CHAR*)cmd.GetColumnName(2) << endl;
printf_s( "%s", (CHAR*)cmd.GetColumnName(2));
printf_s( "%S", (CHAR*)cmd.GetColumnName(2)); //This one works,
//but I really need to store my data, not just print it.
I'm thinking this is a conversion problem from SQL to C++ data types, but I can't put my finger on it. Help?
LPOLESTR is a wchar_t* string (thanks LRiO for confirming that) which is basically unsigned short*. The reason you are getting just the first character is because each character takes up two bytes, and english letters happen to be a NULL byte followed by the ASCII code for that letter, which, when stored in a little-endian format, makes it a C-string with one character (because the bytes are stored backwards).
You need to use wcout to print it:
wcout << cmd.GetColumnName(2);
You can store it like this (along with its length via wcslen):
LPOLESTR ostr = cmd.GetColumnName(2);
size_t ostrlen = wcslen(ostr);