简体   繁体   中英

c++ get the character i from a wstring

I have a small problem, but I can't figure out why..

I have a std::wstring text with a value of L"test"

I then try to print its first character like this:

OutputDebugString(&text[0]);

but the result is test ..

when I use OutputDebugString(&text[1]);

The result is est

I thought that array access should give me the character at a specified location.. Could anybody tell me what I should do or am doing wrong?

I also tried .at(i); with the same result.

Got it:

wchar_t st = text[0];

OutputDebugString(&st);

Alex Reinking stated that this aa better and more safe solution: (as the string then contains a null terminator)

wchar_t st[3] = { text[0], 0x0 };
OutputDebugString(&st[0]);

Thanks for the help

It's because, in memory, the string looks something like this:

      V-- &text[0]
addr: 0x80000000 0x80000001 0x80000002 0x80000003 0x80000004
text: t,         e,         s,         t,         0x00
      ^-- text[0]

So when you ask for the address of text[1] what you get is:

      V-- &text[1]
addr: 0x80000001 0x80000002 0x80000003 0x80000004
text: e,         s,         t,         0x00
      ^-- text[1]

Which leaves you with e,x,t,NULL or the string "ext". The function you're calling will use all the characters up until the terminator.

A string is a series of characters followed by a null terminator.

The OutputDebugString function (and most functions in C and in WinAPI which take strings) accept a pointer to the first character of such a string. The the function keeps printing characters from that location and subsequent locations until it hist the null terminator.

If you only want to act on a single character you either need to call a function which expects a single character, or build a string of length 1 containing that character and a null terminator.

OutputDebugString takes a string, therefore it will start with the address you have given and go all the way until it hits a NULL. To address your specific issue you have to write your own function that will take one character from the string, then put it into a new string, then output that new string.

OutputDebugStringW(text.c_str()); should do what you want

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM