Using wstring for swprintf_s instead of wchar_t * [duplicate] - c++

This question already has answers here:
std::string formatting like sprintf
(44 answers)
Closed 7 years ago.
How can i use std::wstring variable as argument in to swprintf_s instead wchar_t *?
My code is as below but has error:
#include <string>
#include <iostream>
using namespace std;
int main(){
std::wstring msg(20, 0);
swprintf_s( msg.c_str(), 20, L"This is a test for using std::wstring");//this line has error
wcout<< msg<< endl;
return 0;
}

swprintf or swprintf_s writes to the memory pointed by its first parameter. Therefore that parameter cannot be a const char or wchar pointer. But the return value of std::wstring::c_str() is const char* . So you cannot just cast way the const. As mentioned by Jason, if you break the rule, wstring::size() may not return the right value.
What you can do is
wchar_t buffer[20];
swprintf_s(buffer, 20, L"This is a test for using std::wstring");
If you want a std::wstring, you can just use the constructor, like wstring msg(buffer).

Related

why char * works with const only [duplicate]

This question already has answers here:
What is the type of string literals in C and C++?
(4 answers)
Closed 6 months ago.
#include<bits/stdc++.h>
#include<iostream>
using namespace std;
#define nline "\n"
int main(){
//const char *p="hello world";
// court<<p;
char *p="hello world";
cout<<p;
}
C:\Users\Dell\AppData\Roaming\Sublime Text\Packages\User\cses2.cpp: In function 'int main()':
C:\Users\Dell\AppData\Roaming\Sublime Text\Packages\User\cses2.cpp:7:10: warning: ISO C++ forbids converting a string constant to 'char' [-Wwrite-strings]*
char *p="hello world";
^~~~~~~~~~~~~
"hello world" is a const char[12]. A c-array of 12 constant (!) characters (note that one is for the null terminator).
In early C++ standards it was allowed to get a char * to a string literal due to compatibility with C. Though, it was nevertheless forbidden to actually modify the characters of the string literal via the char *.
This changed in C++11 and since then string literals have proper const correctness.
If you do want a string that can be modified, then use a std::string. Note that the pointer you obtain from the literal is not a string, its just a pointer to a (non-modifiable) c-string. If you want a string rather than a pointer to one, you need to use a string.

Display a Variable in MessageBoxW c++ [duplicate]

This question already has answers here:
Convert int to LPCWSTR by using wsprintf
(1 answer)
Display a Variable in MessageBox c++
(5 answers)
Closed 8 years ago.
I have a proplem , like :
Ex :
MessageBoxW(0,L"Đây là ABC (This is ABC)",L"Lỗi (Error)",0);
All ok !
But i want to replace ABC to variable , like it :
char buff[500];
char author[] = "ABC";
sprintf_s(buff,"Đây là %s (This is %s)",author);
MessageBoxW(0, WHAT WILL BE HERE,L"Lỗi (Error)",0);
I hope someone may help !
You can certainly display a variable, but it has to be of the correct type. MessageBoxW takes a LPCWSTR (wide), and a char[] provides a LPCSTR (narrow) instead. So swap out the types accordingly:
WCHAR buff[500]; // WCHAR not char
WCHAR author[] = L"ABC"; // WCHAR not char
swprintf_s(buff, L"Đây là %s (This is %s)", author); // swprintf_s not sprintf_s
MessageBoxW(0, buff, L"Lỗi (Error)", 0);
It's also a good idea to avoid the raw buffers and use a wrapper class such as ATL::CStringW or std::wstring.
(I had some trouble deciding whether to answer this. The related question Why can't I display this string on MessageBox? seems like a duplicate, but it's closed as a duplicate of Cannot convert parameter from 'const char[20]' to 'LPCWSTR' which does not answer this question. In fact its answer is included in this question.)

Conversion of wchar_t* to string [duplicate]

This question already has answers here:
How do I convert wchar_t* to std::string?
(7 answers)
Closed 8 years ago.
How can I convert an wchar_t* array to an std::string varStr in win32 console.
Use wstring, see this code:
// Your wchar_t*
wchar_t* txt = L"Hello World";
wstring ws(txt);
// your new String
string str(ws.begin(), ws.end());
// Show String
cout << str << endl;
You should use the wstring class belonging to the namespace std. It has a constructor which accepts a parameter of the type wchar_t*.
Here is a full example of using this class.
wchar_t* characters=L"Test";
std::wstring string(characters);
You do not have to use a constructor containing String.begin() and String.end() because the constructor of std::wstring automatically allocates memory for storing the array of wchar_t and copies the array to the allocated memory.

Why do I get an exception when I pass a std::string to printf? [duplicate]

This question already has answers here:
printf with std::string?
(9 answers)
Closed 9 years ago.
#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
int main()
{
char a[10] = "asd asd";
char b[10] ="bsd bsd";
string str(a);
str.append(b);
printf("\n--------%s--------\n", str);
return 0;
}
I can't understand why this produces an exception? This program mainly tries to append strings. I get the desired output when using std::cout but not when using printf.
Because std::string is not the same as char const *, which is what the %s format specifies. You need to use the c_str() method to return the pointer expected by printf():
printf("\n--------%s--------\n", str.c_str());
To be more technical, printf() is a function imported from the C world and it expects a "C-style string" (a pointer to a sequence of characters terminated by a null character). std::string::c_str() returns such a pointer so that C++ strings can be used with existing C functions.
c_str(). Have to use style string using this function..
printf() handles c strings (char *), you are using a c++-style string and therefore need to convert between them.
Simply use the c_str() method like so
printf("%s", str.c_str());
printfs %s format specifier is expecting a C style string not a std::string, so you need to use c_str() which return a const char*:
printf("\n--------%s--------\n", str.c_str());
Basically you have undefined behavior since printf will try to access your argument as if it was a pointer to a null terminated C style string. Although, since this is C++ you should just use std::cout is safer.

C++ How do you change an integer to a string? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Alternative to itoa() for converting integer to string C++?
How do you change an integer to a string in c++?
Standard C++ library style:
#include <sstream>
#include <string>
(...)
int number = 5;
std::stringstream ss;
ss << number;
std::string numberAsString(ss.str());
Or if you're lucky enough to be using C++11:
#include <string>
(...)
int number = 5;
std::string numberAsString = std::to_string(number);
You could use snprintf(char *str, size_t size, const char *format, ...) to get a char[], then use string(char*) get string.
Of course,there're other ways.