• 0

String += appending ASCII value instead of char


Question

I've been experimenting with visual C++ having worked in Java for a while. Right now I'm working with a little String manipulation.

I have a Windows Form with a textBox that displays the value of a String. I'm trying to append a char to the String. The problem I'm having is the ASCII value of the String is appended instead of the char itself. So far I haven't been able to find a solution through the resources I've read. Here is an example:

String^ mystring;

char y = 'd';

mystring = "Test";

mystring += y;

textBox->Text = mystring;

The output is "Test100" instead of "Testd" (100 being the ASCII value of d). What should I be doing differently?

10 answers to this question

Recommended Posts

  • 0

I think you will need to do something like this:

mystring += "" + y;

I don't have a compiler in front of me, but you could also try casting y to a string e.g.:

mystring += (string) y;

EDIT: Whoops, just realised this is Visual C++, not C#. Not sure if either of these things will work.

  • 0

It may be that the reason you're seeing the decimal value instead of the ASCII character is because char is a decimal type. It is a decimal type just large enough to hold an ASCII character: 8-bits. Try referencing it as a pointer instead of a single character to make it a C-style string.

  • Like 1
  • 0

Is 'String' a Microsoft-centric data type or did you mistype the name of the standard 'string' class? The string class in the standard library can append single characters, C-style strings, and standard strings using the '+=' operator.

Without knowing the data type of 'textBox->Text', I'm assuming that something like the following will work:


std::string mystring;
char y = 'd';

mystring = "Test";
mystring += y;
textBox->Text = mystring.c_str();
[/CODE]

Alternatively, you could forgo the niceness of the string class and use only C-style strings. Your example would then look something like this:

[CODE]
char mystring[50];
char y = 'd';

strcpy( mystring, "Test" );
strncat( mystring, &y, 1 );
textBox->Text = mystring;
[/CODE]

  • Like 1
  • 0

String^ mystring;
char y = 'd';
mystring = "Test";
mystring += y;
textBox->Text = mystring;[/CODE]

This is C++/CLI. The caret "^" on a type name is not C++ syntax, it denotes a managed type, here System::String. If you want to learn C++, make sure you create an empty C++ project, not a "CLR" project. You won't be able to work directly with Winforms with C++; if working with Winforms is what you want, learn C# instead. I strongly doubt you want to learn C++/CLI, it is more complicated than you can imagine and it doesn't serve much purpose besides building bridges between the native and the managed world.

Anyway, with System::String you can't append a char to a string using the += operator, however you could call ToString() on the character and append that isntead, i.e.

[CODE]mystring += y->ToString();[/CODE]

But really, run from C++/CLI while there is still time. File -> New -> Project -> Visual C++ -> General -> Empty Project. Now you're doing real, ISO C++. It's complicated enough by itself.

  • Like 5
  • 0

.NET uses unicode characters. Use wchar_t instead of char.

wchar_t y = L'd';[/CODE]

It most likely chooses int (System::Int32) as the closest conversion for char as a result, resulting in the decimal number.

If you really want to use char throughout your code, then you can do something similar to Dr_Asik's suggestion by using Convert::ToString:

[CODE]char y = 'd';
String ^value = Convert::ToString(y);[/CODE]

This link explains the mapping of types to the CLI: http://www.c-sharpcorner.com/uploadfile/b942f9/cppcli-for-the-C-Sharp-programmer/ , which is why it maps to a number rather than a character (it does not widen to the number, rather it widens to an integer).

  • Like 1
  • 0

Scrapped everything and redid the project in C#. Holy crap was it easier. I was thinking I could do it in C++ since that's what I used in college (command line progs only). That Visual C++/CLI stuff sucked. Knowing Java I was pretty much able to code in C# without having to look up much of anything. Came up with this little Class for creating a password:


class SecurePassword
{
private String password;
private int length;
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
Random random = new Random();
public void generatePassword(bool useUpper, bool useNumber)
{
char ch;
int i;
int type;
password = "";
for (i = 0; i < this.length; i++)
{
type = (random.Next(0, 4));
if (type == 0 && useUpper)
ch = getRandomUpperChar();
else if (type == 1 && useNumber)
ch = getRandomDigit();
else
ch = getRandomLowerChar();

password += ch;
}
}
public char getRandomDigit()
{
byte[] byteCh = new byte[4];
double range;
uint intCh;
rng.GetBytes(byteCh);
intCh = BitConverter.ToUInt32(byteCh, 0);
range = intCh / 4294967296.0;
intCh = (uint)(range * 10);
return Convert.ToChar(intCh + 48);
}
public char getRandomLowerChar()
{
byte[] byteCh = new byte[4];
double range;
uint intCh;
rng.GetBytes(byteCh);
intCh = BitConverter.ToUInt32(byteCh, 0);
range = intCh / 4294967296.0;
intCh = (uint)(range * 26);
return Convert.ToChar(intCh + 97);
}
public char getRandomUpperChar()
{
byte[] byteCh = new byte[4];
double range;
uint intCh;
rng.GetBytes(byteCh);
intCh = BitConverter.ToUInt32(byteCh, 0);
range = intCh / 4294967296.0;
intCh = (uint)(range * 26);
return Convert.ToChar(intCh + 65);
}
public String getPassword()
{
return password;
}
public void setLength(int len)
{
length = len;
}
}
[/CODE]

Had a little hiccup converting the byte array to a character in the range I wanted, Im sure my solution is a bit sloppy. I wanted to use the secure random methods instead of just Random.Next(min, max).

  • 0
  On 02/10/2012 at 19:21, Lord Method Man said:

Had a little hiccup converting the byte array to a character in the range I wanted, Im sure my solution is a bit sloppy. I wanted to use the secure random methods instead of just Random.Next(min, max).

Note: you're still using Random.Next(...) in your main loop.

Also, you could probably simplify the code a lot with your bytes-to-number conversion being extracted into a separate function.

private char getCharacter(uint start, uint range)
{
    byte[] bytes = new byte[1];

    // realistically, given the expected ranges (not even a full byte), you could use a single byte
    rng.GetBytes(bytes);

    return Convert.ToChar(start + bytes[0] % range);
}
[/CODE]

Any random lowercase character: [code]ch = getCharacter((uint)'a', 26);

Any random uppercase character:

ch = getCharacter((uint)'A', 26);

Any random number character:

ch = getCharacter((uint)'0', 10);

This topic is now closed to further replies.
  • Posts

    • Guilty is used as a regular English term here, not the legal term
    • AnyDesk 9.5.6 by Razvan Serea AnyDesk is a fast remote desktop system and enables users to access their data, images, videos and applications from anywhere and at any time, and also to share it with others. AnyDesk is the first remote desktop software that doesn't require you to think about what you can do. CAD, video editing or simply working comfortably with an office suite for hours are just a few examples. AnyDesk is designed for modern multi-core CPUs. Most of AnyDesk's image processing is done con­currently. This way, AnyDesk can utilize up to 90% of modern CPUs. AnyDesk works across multiple platforms and operating systems: Windows, Linux, Free BSD, Mac OS, iOS and Android. Just five megabytes - downloaded in a glimpse, sent via email, or fired up from your USB drive, AnyDesk will turn any desktop into your desktop in se­conds. No administrative privileges or installation needed. AnyDesk 9.5.6 changelog: Features Implemented Discovery section in AnyDesk One Implemented multi-selection in Monitoring list views using Shift-Click Implemented URL handler for navigation Bugfixes Fixed crash when initialization of gles failed Fixed crash due to uncaught exceptions when registering internal services Fixed crash due to uncaught exceptions when registering internal services Fixed crash when adding device to favourites Fixed crash when starting Screen Recording Fixed bug that lead to showing incorrect Alerts in Monitoring when viewing specific devices Fixed bug that lead to interpreting right clicks as left clicks Fixed handling of double and triple clicks for middle and right mouse buttons Other changes Redesigned the authors' section in About AnyDesk panel Improved initialization of rendering components so that it is only done when needed Removed some false positive warning traces Download: AnyDesk 9.5.6 | macOS ~14.0 MB (Free for private use, paid upgrade available) Links: AnyDesk Home Page | Other platforms | Release History | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • President Trump says TikTok deadline will ‘probably' be extended again by Sagar Naresh Bhavsar It appears that the Trump administration is quite keen on allowing TikTok to continue its operations in the U.S. The platform was briefly banned in the U.S. on January 19 for 14 hours. But as soon as Donald Trump assumed office as the 47th President of the U.S. on January 20, he signed an executive order to give a reprieve of 75 days to TikTok. During this period, TikTok had to separate itself from its Chinese parent, ByteDance, and find a U.S. buyer. Several U.S. companies, including Microsoft, Oracle, Perplexity AI, and Amazon, reportedly showed interest in buying the U.S. assets of TikTok. While President Trump hinted that a deal could soon come through, nothing materialised. As the 75-day deadline was about to expire on April 5, Trump signed another executive order on April 4, granting TikTok another 75-day extension. Now, with the second deadline nearing its end on June 19, it seems like President Trump is still unwilling to let TikTok shut down in the U.S. According to Reuters, U.S. President Trump has said that he would likely offer another extension to ByteDance-owned short video platform TikTok to divest its U.S. assets. Answering reporters on Air Force One on Tuesday, when asked about extending the deadline, Trump said; If announced, it will be for the third time, TikTok gets a lifeline to continue its operations in the U.S. While there is no clarity on how many extensions the company might receive, it's evident that President Trump wants TikTok to find a solution for its U.S. assets. Interestingly, he wanted to ban TikTok during his first Presidential term. However, things changed as Meta banned him from its platforms after the January 6, 2024, Capitol Attack. Trump then joined TikTok and appreciated the platform to help him reach a young audience. For now, TikTok's fate still hangs in the balance. Let us know in the comments below what you think about this development. Image by rafapress via Depositphotos
  • Recent Achievements

    • Week One Done
      Rhydderch earned a badge
      Week One Done
    • Experienced
      dismuter went up a rank
      Experienced
    • One Month Later
      mevinyavin earned a badge
      One Month Later
    • Week One Done
      rozermack875 earned a badge
      Week One Done
    • Week One Done
      oneworldtechnologies earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      698
    2. 2
      ATLien_0
      272
    3. 3
      Michael Scrip
      214
    4. 4
      +FloatingFatMan
      186
    5. 5
      Steven P.
      145
  • Tell a friend

    Love Neowin? Tell a friend!