• 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.

  • 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

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

    • I must admit, this is probably the only game at the moment where I can see that $80 price point being ok. The issue will be when other developers think they can get away with it with half of the work.
    • Google Wallet expands TSA PreCheck Touchless ID access to more travellers by Fiza Ali Google has announced that Google Wallet is becoming the first digital wallet to integrate with TSA PreCheck Touchless ID. It is a programme that lets eligible travellers move through participating airport security checkpoints using facial recognition instead of showing a physical ID or boarding pass. While the TSA PreCheck Touchless ID programme has been available for some time, using it hasn't always been straightforward. The programme currently operates at 65 airports across the US, but participation has largely depended on flying with a limited number of airlines. Travellers also had to upload passport information separately through participating carriers. Now, the tech giant's new integration is designed to remove some of those extra steps. With the update rolling out in the coming weeks, travellers with TSA PreCheck membership will be able to enrol in Touchless ID through Google Wallet and use the service with any of the 100 airlines participating in the programme. Rather than repeatedly submitting identification details, users can store a digital ID in Google Wallet and use it to streamline future trips. Setting up the feature is relatively straightforward as well. The process starts with users creating a digital ID in Google Wallet using their passport information. After checking in for a flight and saving a boarding pass to the app, eligible travellers will see a "Get started" option that directs them to the TSA enrolment process. Once users choose to share their ID pass and boarding pass information with the TSA for a specific trip, the agency will verify the enrolment. If approved, a TSA PreCheck Touchless ID indicator will appear on the boarding pass stored in Google Wallet, signalling that the traveller can use designated express Touchless ID lanes at participating airports. As privacy and security are likely to be key considerations for many travellers, Google says users must explicitly opt in before any information is shared with the TSA, and authentication is required through a device PIN, pattern, or biometric verification. The company also notes that digital IDs stored in Google Wallet remain encrypted and are kept on the user's device. For frequent flyers who already use TSA PreCheck, the new integration could remove a few more steps from the airport security process, making travel slightly faster and a little less cumbersome.
    • Even though MS had to sunset the Windows Subsystem for Android, you can apparently use BlueStacks to run Android in Windows now. I haven't tested this yet, so if anyone has any feedback, I'd love to hear it.
    • Or, if you want to teach your kids how to hallucinate and lie like AI slop, introduce them to a Crazy MAGA Grandpa on LSD.
    • Ventoy 1.1.14 by Razvan Serea Ventoy is an open source tool to create bootable USB drive for ISO/WIM/IMG/VHD(x)/EFI files. With Ventoy, you don't need to format the disk over and over, you just need to copy the ISO/WIM/IMG/VHD(x)EFI files to the USB drive and boot them directly. You can copy many files at a time and ventoy will give you a boot menu to select them. Both Legacy BIOS and UEFI are supported in the same way. Most type of OS supported (Windows/WinPE/Linux/Unix/Vmware/Xen...) Ventoy features: 100% open source Simple to use Fast (limited only by the speed of copying iso file) Directly boot from ISO/WIM/IMG/VHD(x)/EFI file, no extraction needed Legacy + UEFI supported in the same way UEFI Secure Boot supported (since 1.0.07+) Persistence supported (since 1.0.11+) MBR and GPT partition style supported (1.0.15+) WIM files boot supported (Legacy + UEFI) (1.0.12+) IMG files boot supported (Legacy + UEFI) (1.0.19+) Auto installation supported (1.0.09+) File injection supported (1.0.16+) ISO files larger than 4GB supported Native boot menu style for Legacy & UEFI Most type of OS supported(Windows/WinPE/Linux/Unix/Vmware/Xen...), 550+ iso files tested Not only boot but also complete installation process ISO files can be listed in List mode/TreeView mode Linux vDisk boot supported (vdi/vhd/raw) "Ventoy Compatible" concept Plugin Framework Menu Alias/Menu Style/Customized Menu supported USB drive write-protected support USB normal use unaffected Data nondestructive during version upgrade No need to update Ventoy when a new distro is released Ventoy 1.1.14 changelog: Update secure boot shim file to solve the UEFI CA 2023 issue. The new release use a new CA, so you need to enroll the new key for the first boot time. VentoyPlugson update synchronously. Global control plugin add a VTOY_SECURE_BOOT_POLICY option. Notes Download: Ventoy 1.1.14 | 15.9 MB (Open Source) Download: Ventoy Live CD | 187.0 MB Link: Ventoy Home Page | Project Page @GitHub | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Dedicated
      Scoobystu earned a badge
      Dedicated
    • First Post
      Tom Schmidt earned a badge
      First Post
    • One Month Later
      D0nn13 earned a badge
      One Month Later
    • Rookie
      +ChiefOfNeo went up a rank
      Rookie
    • One Year In
      Tom Schmidt earned a badge
      One Year In
  • Popular Contributors

    1. 1
      +primortal
      457
    2. 2
      +Edouard
      177
    3. 3
      PsYcHoKiLLa
      123
    4. 4
      Michael Scrip
      83
    5. 5
      Xenon
      76
  • Tell a friend

    Love Neowin? Tell a friend!