0

So I'm having trouble concatenating strings and chars and then displaying them using the message box because my characters get printed as numbers, and when I try to convert them to string no matter where or how the message box throws an error! Any help is appreciated!

MessageBox::Show("The most common letter is \"" + letters[biggetsNumberIndex] + "\".");
// Simplified version: MessageBox::Show("string" + 'c' + "string");
Darkon
  • 1
  • 1
  • [How to concatenate two strings in C++?](https://stackoverflow.com/questions/15319859/how-to-concatenate-two-strings-in-c) – Drew Dormann Feb 14 '22 at 18:09
  • It's the character that causes problems. I can concatenate them just fine, but the characters get displayed as numbers. – Darkon Feb 14 '22 at 18:16
  • Have you defined the array as, e.g., `array^ arr = { 'a', 'b', 'c' };`? In this case, `MessageBox::Show("Last char is the " + arr[2] + " letter");` will show `Last char is the c letter` – Jimi Feb 14 '22 at 18:31
  • It would be the same in case `letters` is `String^ letters = "abc";` – Jimi Feb 14 '22 at 18:37
  • I just used char letters[4] = {'a', 'b', 'c'}, But also tried using simple std::string letters = "abc" – Darkon Feb 14 '22 at 18:50
  • I highly recommend building the string before calling `Show()`. This allows you to place a breaking at `Show()` and see the string contents. – Thomas Matthews Feb 14 '22 at 19:06

1 Answers1

0

I managed to fix it thanks to "Jimi" I changed the "letters" variable instead of character array or std::string I used String^

// Bad
std::string letters = "abcdefghijklmnopqrstuvwxyz";

// Good
String^ letters = "abcdefghijklmnopqrstuvwxyz";
Darkon
  • 1
  • 1
  • It's not *bad*, it's just *unmanaged*. You could have `const char* letters = "abcdefghijklmnopqrstuvwxyz";`, which could be *transformed* as `String^ lLetters = gcnew String(letters);` and `MessageBox::Show(L"string " + lLetters[2] + L" string");` -- With `std::string letters = "abcdefghijklmnopqrstuvwxyz";`, you can marshal as `String^ lLetters = marshal_as(letters);` <- careful here since you can mess up some macros if you handle COM objects, as (quite common) `IDataObject`s, when you `#include ` – Jimi Feb 14 '22 at 19:25
  • Yes, I know it's not bad it's just to make it clear. Anyway, it was the simplest solution. Thanks for the info. – Darkon Feb 19 '22 at 23:28