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

    • Offering real value takes effort. It's far more efficient to create a fake crisis, sell the Band-Aid, and host a keynote about how you're saving the world.
    • Windows 11 gets a new way to fix boot issues, Widgets improvements, more in build 26200.5622 by Taras Buria Microsoft is kicking off this week with a duo of new Windows 11 preview builds. Those in the Dev Channel received build 26200.5622 (KB5058512), which introduces several improvements and new features, including a new way to recover from boot issues, widget improvements, new features for Click to Do, and more. Users with Copilot+ PCs can now try a new Click to Do feature. It lets you click a sentence in an email or any other portion of text on your screen and click "Draft with Copilot in Word" to create a document based on the selected text and your instructions. Note that this feature requires a Microsoft 365 subscription. Also, Click to Do now supports French and Spanish languages for the rewriting tool, and text actions are now available in German, Italian, and Portuguese. Next is the big one. Quick Machine Recovery now has its own section in the Settings app. Announced at Ignite 2024, this feature lets you quickly resolve boot issues by applying fixes and patches within the Windows Recovery Environment. The new page enables you to check and configure the status of QMR. Windows Insiders can try QMR in action with test mode. Windows Widgets now feature multiple boards, allowing you to switch between widget-only view and a mix of widgets and news. Other changes include the following: The "Open with" dialog now displays app recommendations, allowing you to discover more apps that support the selected file. Phone Link now groups notifications in the start menu and lets you initiate screen mirroring (Android-only) with a single click. Connected iPhones can also display memories and recently synced photos. The Settings app now has a better alignment for the search bar on Copilot+ PCs, redesigned dialogs for entering your product key, troubleshooting activation, phone activation, and retail demo to match the Windows 11 visuals. Also, there is now a new Device Card for the Home page where you can see a brief rundown of your PC's specs. Now, here is what was fixed (these fixes are rolling out gradually): The following fixes are rolling out for improved Windows Search on Copilot+ PCs: Fixed an underlying crash causing semantic indexing to not work for some Insiders in the last couple flights. [Start menu] There have been some underlying improvements which should help address the issue where clicking your profile picture wasn’t opening the Account Manager for some Insiders after the latest flights. If you’re continuing to experience issues, please file feedback. Fixed an issue causing Start menu to crash on launch for some Insiders in the latest flights. [File Explorer] Fixed an issue where if you opened the “…” menu in the File Explorer address bar to show the full list of folders for the current path, the dropdown might be cut off and the bottom of it inaccessible. Fixed an issue which was causing File Explorer to crash doing various actions in the latest flights, including when deleting files for some Insiders. Fixed an issue where the recommended section in File Explorer wasn’t expanding when using the right arrow key. Fixed an issue which could lead to duplicate access keys in the File Explorer context menu. The following are fixes for AI actions in File Explorer: Fixed the issue where the action result canvas displayed text from left to right for AI actions for Microsoft 365 files w [Task Manager] Fixed an issue where after adding the new CPU Utility column, you might notice that System Idle Process always showed as 0. Fixed an issue where the CPU graphs in the Performance page were still using the old CPU utility calculations. [Narrator] Fixed an issue where the Describe image feature of narrator wasn’t working. [Voice Access] Fixed an issue where support for more descriptive and flexible language on Copilot+ PCs wasn’t working as expected. [Settings] Fixed an underlying issue related to Bluetooth which could cause Settings or Quick Settings to crash on launch for some people. Fixed an issue with Quick Settings where if you clicked the top third of the buttons in the top row, it wouldn’t work. [Other] Fixed an issue with msftedit.dll which was causing apps like Sticky Notes and Dxdiag to crash in certain cases for people using Hebrew or Arabic display languages. And there is a single fix that is available for everyone in the Dev Channel: [General] We have mitigated the issue where if Virtualization Based Security is enabled, applications dependent on virtualization, such as VMware Workstation, would lose the ability to run unless the “Windows Hypervisor Platform” Windows optional component is installed on the system. Finally, here is the list of known bugs: [General] After you do a PC reset under Settings > System > Recovery, your build version may incorrectly show as Build 26100 instead of Build 26200. This will not prevent you from getting future Dev Channel updates, which will resolve this issue. The option to reset your PC under Settings > System > Recovery will not work on this build. [Xbox Controllers] Some Insiders are experiencing an issue where using their Xbox Controller via Bluetooth is causing their PC to bugcheck. Here is how to resolve the issue. Open Device Manager by searching for it via the search box on your taskbar. Once Device Manager is open, click on “View” and then “Devices by Driver”. Find the driver named “oemXXX.inf (XboxGameControllerDriver.inf)” where the “XXX” will be a specific number on your PC. Right-click on that driver and click “Uninstall”. [Click to Do (Preview)] The following known issues will be fixed in future updates to Windows Insiders: Windows Insiders on AMD or Intel™-powered Copilot+ PCs may experience long wait times on the first attempt to perform intelligent text actions in Click to Do after a new build or model update. [Improved Windows Search] [REMINDER] For improved Windows Search on Copilot+ PCs, it is recommended that you plug in your Copilot+ PC for the initial search indexing to get completed. You can check your search indexing status under Settings > Privacy & security > Searching Windows. [Taskbar & System Tray] [NEW] In some cases, taskbar icons may appear small even though the setting to show smaller taskbar buttons is configured as “never”. [File Explorer] The following are known issues for AI actions in File Explorer: Narrator scan mode may not work properly in the action result canvas window for the Summarize AI action for Microsoft 365 files when reading bulleted lists. As a workaround, you can use Caps + Right key to navigate. [Widgets] Until we complete support for pinning in the new widgets board experience, pinning reverts you back to the previous experience. [Graphics] [NEW] When connecting your PC to some older Dolby Vision displays, in some cases you might see severe discoloration. You can navigate to Settings > System > Display > HDR turn off “Use Dolby Vision mode” as a workaround to resolve the issue or disconnect the display. You can find the announcement post on the official Windows Blogs website.
    • Photo Variants 2.2 by Razvan Serea Photo Variants is an all-in-one photo editor for Windows. Quickly cull, import, and edit your images with powerful tools. Enjoy full layer support, precise retouching features, and a wide range of filters and color adjustments. Create multiple versions of a photo instantly with presets, or design from scratch using vector graphics and advanced editing options. Free for personal and commercial use. Photo Variants key Features: Advanced Adjustment Tools: Provides precise control over image modifications. ​ Extensive Filter Collection: Offers over 99 photo filters to apply various effects. ​ Animated Photo Effects: Enables the addition of dynamic elements to images. ​ Automatic Face Retouching: Includes features for enhancing facial features automatically. ​ Support for Multiple Formats: Compatible with over 100 graphic formats, including RAW and PSD files, allowing users to open, edit, and save in these formats. ​ Drawing and Transformation Tools: Facilitates freehand drawing, erasing, filling, cropping, resizing, rotating, and flipping images. Photo Variants supports a wide array of image formats, making it a versatile tool for all your editing needs. Key supported formats include: Raster Formats: .jpeg, .jpg, .png, .bmp, .gif, .tiff, .webp, .ico, .pcx. Camera RAW: .crw, .cr2, .dng, .nef, .raf, .arw, .orf, .x3f, .raw. Professional Formats: .psd, .ai, .svg, .tga, .pdf, .pcl. Specialized Formats: .dicom, .dcm, .heic, .heif, .avif, .exr, .dds. Other: .wmf, .emf, .xps, .jpeg2000 (.jp2)...etc... With support for these formats, Photo Variants offers seamless editing and flexibility for photographers, designers, and creatives. Photo Variants 2.2 changes: Added the ability to save and export all images at once. New option in the RAW import window. Download: Photo Variants 2.2 | 64.2 MB (Freeware) View: Photo Variants Home page | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Something is either premium or not. No such thing as premium lite. They just made fool out of the subscribers who took the lite subscription for some convenience.
    • And not to mention the junk foods, fast foods and processed foods full of chemicals.
  • Recent Achievements

    • Week One Done
      Nullun earned a badge
      Week One Done
    • First Post
      sultangris earned a badge
      First Post
    • Reacting Well
      sultangris earned a badge
      Reacting Well
    • First Post
      ClarkB earned a badge
      First Post
    • Week One Done
      Epaminombas earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      170
    2. 2
      ATLien_0
      125
    3. 3
      snowy owl
      120
    4. 4
      Xenon
      118
    5. 5
      +Edouard
      100
  • Tell a friend

    Love Neowin? Tell a friend!