• 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

    • Microsoft's new AI tools: What "Researcher" and "Analyst" mean for your work by Paul Hill Microsoft has announced the general availability of two new reasoning AI agents called Researcher and Analyst. Both were previously available for Microsoft 365 Copilot Frontier members, but now they’re available for all Microsoft 365 Copilot license holders. Researcher is capable of multi-step research by combining OpenAI’s deep research model with Microsoft 365 Copilot’s orchestration and deep search capabilities. The Analyst agent can think like a data scientist, giving you insights in minutes from raw data. Analyst is built on OpenAI’s o3-mini. Microsoft says it can run Python to tackle the most complex data queries and you can view the code it’s running to verify its work in real time. Who it affects, and how While Frontier members have had access to these agents since April, they’ve only just been announced for general availability. The Copilot in question is not Microsoft’s free Copilot either, but the Copilot that comes as part of Microsoft 365 and includes additional features. To access it, you will have to pay for a $30 per month paid yearly subscription. Existing customers should now have access to both of these agents. While there is certainly angst in the world about the influence of AI on our jobs, Microsoft still maintains that it’s an assistant tool. These two new agents look set to benefit professionals across a range of roles including researchers and strategists, data analysts and scientists, sales and marketing teams, and anyone who just wants to summarize or synthesize information fast. The Researcher agent is helpful for gathering insights, preparing for negotiations, and assessing impacts such as the impact of tariffs on businesses. Meanwhile the Analyst agent can be used to convert raw data into actionable insights, identifying customer behaviors, and visualizing trends. It’s not all good news, Microsoft does have some limitations in place to ensure reliability of its service for all customers. The Redmond giant explains that the pre-pinned agents can run up to 25 combined queries per month - so that’s not 25 queries per agent, it’s for both together, each month. Additionally, Researcher supports 37 languages, but Analyst only supports eight, with more coming soon. Why it's happening Agents have been all the rage since the end of 2024 when figures in big tech declared that 2025 would be the year of agentic AI. Agents are capable of multi-step work and bring us closer to the goal of artificial general intelligence (AGI). These agents that Microsoft has unveiled are possible now thanks to the development of OpenAI’s deep research model and o3-mini, which also reasons. Earlier this year, Microsoft declared that it wanted to empower employees everywhere with AI agents and the release of Researcher and Analyst goes a long way in doing this. They will be beneficial for employees in many different fields and have the potential to free up a lot of time for more beneficial work. Customers in the Frontier program, Microsoft said, found these new tools to be highly effective for complex analytical work. This is great for Microsoft financially because it shows clear demand for such tools, justifying AI’s upfront development costs. These agents also help Microsoft keep up against the competition, which is also aggressively pursuing agents. What to watch for Microsoft said that its Researcher agent is much more accurate than everything that came before, thanks to the time it spends thinking about its answer. However, AI does still possess the ability, just like humans, to make mistakes. Verifying the creations of these agents is still crucial when it comes to anything mission critical. The Analyst agent’s ability to let the user see the steps and which Python code it executes is very good for transparency and can help combat errors if things ever start to go wrong with the agent’s reasoning. This could help to build trust among customers who need to use the Analyst agent and could set Microsoft’s offering apart from the competition, giving it an edge. Another thing customers should be aware of is the prompt they use matters. Microsoft tries to guide customers along with sample prompts but to get the most from these tools, users will need to know how to create effective and precise prompts. The good thing is that these bots are spoken with natural language, so it’s just a matter of being articulate and precise when you give a prompt. It will certainly be interesting to see how agents like these continue to affect employees’ job security in the future. While AI can certainly be helpful, if it develops to a point where an employer can effectively hire AI for a low cost to do the same work, then it could lead to massive displacement, with not enough new jobs for people to move into. This point has recently been elucidated by Anthropic’s CEO Dario Amodei. Source: Microsoft
    • I'm wondering if they are doing this as a "backup" in case CISA ceases to exist. It almost did recently due to funding and it's future is shaky. CISA - https://www.cisa.gov/known-exploited-vulnerabilities-catalog Example "CVE-2023-39780" https://www.cve.org/CVERecord?id=CVE-2023-39780 ASUS RT-AX55 Routers OS Command Injection Vulnerability
    • Over regulation is bad. That's why the EU is behind the US. But, it's a good thing the EU stepped in, in this case.
  • Recent Achievements

    • One Year In
      WaynesWorld earned a badge
      One Year In
    • First Post
      chriskinney317 earned a badge
      First Post
    • 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
  • Popular Contributors

    1. 1
      +primortal
      173
    2. 2
      ATLien_0
      125
    3. 3
      snowy owl
      123
    4. 4
      Xenon
      118
    5. 5
      +Edouard
      91
  • Tell a friend

    Love Neowin? Tell a friend!