I have a function that takes only one LPWSTR as argument. However, I need to add integer to the end of it.
Here's an example pseudocode:
int theNumber = 5;
LPWSTR myLPWSTR = L"Number is: ";
/* Add theNumber to myLPWSTR */
myFunction(myLPWSTR);
How to do this?
I have already tried converting int to LPWSTR and then concatenate them but I didn't succeed. I've tried this for the whole morning but just can't figure out how to do this.
I've tried eg. wsprintf, _itow_s, c_str and pretty much everything I know of - but just can't do it and it's getting really frustrating.
Someone please help.
Assuming the function really takes a LPWSTR and not a LPCWSTR (i.e. it can modify the string passed in), you'll have to do something like this:
int theNumber = 5;
std::wostringstream s;
s << L"Number is: " << theNumber;
std::wstring str = s.str();
std::vector<wchar_t> buf(str.begin(), str.end());
buf.push_back(0);
myFunctions(&buf[0]);
This is necessary because you need to supply a properly nul-terminated and modifiable buffer of wchar_ts. str.c_str() is nul-terminated but not modifiable. &str[0] is modifiable but not (guaranteed to be) nul-terminated.
If you can use C++11:
std::wstring str = L"Number is: ";
str += std::to_wstring(42);
myFunction( str.data() );
if not:
std::wstringstream ss;
ss << L"Number is: " << 42;
myFunction( ss.str().c_str() );
Don't forget to include string and sstream.
Related
I was wondering how I could convert an int to a string and then add it to an existin string. i.e.
std::string s = "Hello";
//convert 1 to string here
//add the string 1 to s
I hope I'm making sense. Thank you very much in advance for any answer.
If the number you want to append is an integer or floating point variable, then use std::to_string and simply "add" it:
int some_number = 123;
std::string some_string = "foo";
some_string += std::to_string(some_number);
std::cout << some_string << '\n';
Should output
foo123
The "modern" way is to use std::to_string(1). In fact, various overloads of std::to_string exist for different number types.
Putting this together you can write std::string s = "Hello" + std::to_string(1);
Alternatively you can use std::stringstream which can be faster due to fewer string concatenation operations which can be expensive:
std::stringstream s;
s << "Hello" << 1;
// s.str() extracts the string
I have a question about a char array:
I have a form '"1"+lapcounter+":"+seconds' that must come in a char array.
How can i fill this array in this form?
Thanks
If you mean you have some numeric variables which you want to format into a string, use a string-stream for that:
std::stringstream ss;
ss << "1" << lapcounter << ":" << seconds";
Now you can extract a string from that:
std::string s = ss.str();
and if you really want a character array for some reason (which I'm sure you don't)
char const * cs = s.c_str();
Use sprintf, or snprintf. This function works similar to printf but instead of standard output, the output will go to char array you specified. For example:
char buffer[32];
snprintf(buffer, sizeof(buffer), "1%d:%d", lapcounter, seconds);
to_string is used like this:
#include <iostream>
#include <string>
int main()
{
int lapcounter = 23;
std::string str("1");
str.append(std::to_string(lapcounter ));
str.append(":seconds");
std::cout << str << std::endl;
}
prints
123:seconds
if you really need a char array you get that from ss.c_str()
I'm sure this is an easy question for most but I'm having trouble trying to figure out why I can't manipulate this sting and better yet how I should go about doing it. So for example we have:
char *str1="Hello World";
All I want to do is manipulate the string that is being pointed to by 'str1'. For example, as shown below, I could output the string and see the original. Then I could add a null character in there and shorten it.
cout << str1 << '\n';
str1[5] = '\0';
cout << str1;
I've also tried:
cout << str1 << '\n';
*(str1+4) = '\0';
cout << str1;
Either way I'm hoping to see something like this:
Hello World
Hello
The error I'm getting in both cases is when I try to alter the string. I know it would be easier to just declare str1 as an array (char str1[] = ....) but I'm given the constraint of having to use the dreaded char *
String literals are stored in read-only memory. You cannot modify them. In fact, in modern C++, attempting to initialise str1 the way you did will give an error. It should be a const char*:
const char* str1 = "Hello World";
This makes it clear that you shouldn't be modifying the chars.
If you want a copy of the string that you can manipulate, you should make str1 an array:
char str1[] = "Hello World";
When you initialise an array with a string literal, the characters are copied into the array.
So after all of the help I've received from you all I went with first determining the length of the strings, initializing an array of the same size+1, and then iterating through the original to save it into an array. Then I was able to manipulate it as i pleased.
int someFunc(char *inpStr){
int counter = 0;
//Find the length of the input string
while(inpStr[counter]!='\0'){counter++;}
//Input initialize an array of same size
char strArray[counter+1];
//Copy whats in the char * to the array and make sure it ends with null
for(int i=0;i<=counter;i++){strArray[i]=*(inpStr+i);}
strArray[counter]='\0';
.....
return 0;
}
Thanks for all the help!
Why you cannot change the str1 has been explained aptly by Joseph. But still if you want to modify it you can use something like this:
char *str = "hello";
char *ptr = new char[strlen(str)+1];
strcpy(ptr,str);
ptr[2] = 'd';
str = ptr;
I hope this solves your problem.
I am trying to use the new stringstreams method to convert certain float+int combination into certain format but trying to see if there is any better way to handle this:
Now using //string String = static_cast( &(ostringstream() << Number) )->str(); kind of mode - How can I get this stored into a string form of the format - "1.10(3)". Precision is equal to decimals. The catch here is none of these values are constants. Even if the solution can't be an in-line function or stringstreams - it's fine as long as it's generic enough. Also note that in the end the plan is to use this string into GDI text string.
Thanks in advance - if any one can help.
Here is my current sample code(and looking for an alternate efficient way to get this done):
string Convert(float number,int decimals)
{
std::ostringstream buff;
buff<<setprecision(decimals)<<fixed<<number;
return buff.str();
}
float f=1.1; // this can have any values from 1,1.5 or 1.52
int decimals=2; //dynamic number - calculated by other means - not a fixed number
int i=3; // some dynamic number as well - calculated by other means
string s=Convert(f,decimals)+"("+Convert(i,0)+")"; // output - 1.10(3)
You can use std::fixed, std::setprecision, std::setw and std::setfill defined in <iomanip> :
float f=1.1;
int decimals=2;
int i=3;
ostringstream ss;
ss << std::fixed << std::setprecision(decimals) << f << '(' << i << ')';
string str = ss.str();
Which outputs :
1.10(3)
You can also configure the stringstream and keep this configuration :
ostringstream ss;
ss.precision(5);
ss.setf(std::ios::fixed);
EDIT
You can still do this in one line if you really want to :
string str = ((ostringstream&)(ostringstream() << fixed << setprecision(decimals) << f << '(' << i << ')')).str();
If you want a LPCWSTR (const wchar_t *) instead of a LPCSTR (const char*) you should use wstringstream instead of stringstream.
ostringstream ss;
string str = ss.str();
LPCSTR* c_str = str.c_str();
wostringstream wss;
wstring wstr = wss.str();
LPCWSTR* wc_str = wstr.c_str();
If you want a LPCTSTR (LPCSTR or LPCWSTR if UNICODE is defined), you can use some typedef like this :
typedef std::basic_string<TCHAR> tstring;
typedef std::basic_ostringstream<TCHAR , std::char_traits<TCHAR> > tstringstream;
tostringstream tss;
tstring tstr = tss.str();
LPCTSTR* tc_str = tstr.c_str();
TCHAR is a char * if UNICODE is not defined in your project and a wchar_t * if UNICODE is defined.
everybody I have problem with string concatenation in C++, here is my code
map<double, string> fracs;
for(int d=1; d<=N; d++)
for(int n=0; n<=d; n++)
if(gcd(n, d)==1){
string s = n+"/"+d;// this does not work in C++ but works in Java
fracs.insert(make_pair((double)(n/d), s));
}
How can I fix my code?
Try like this.
stringstream os;
os << n << "/" << d;
string s =os.str();
In C++ you have to convert an int to a string before you can concatenate it with another string using the + operator.
See Easiest way to convert int to string in C++.
Use streams, in your case, a stringstream:
#include <sstream>
...
std::stringstream ss;
ss << n << '/' << d;
Later, when done with your work, you can store it as an ordinary string:
const std::string s = ss.str();
Important (side-) note: Never do
const char *s = ss.str().c_str();
stringstream::str() produces a temporary std::string, and according to the standard, temporaries live until the end of the expression. Then, std::string::c_str() gives you a pointer to a null-terminated string, but according to The Holy Law, that C-style-string becomes invalid once the std::string (from which you receved it) changes.
It might work this time, and next time, and even on QA, but explodes right in the face of your most valuable customer.
The std::string must survive until the battle is over:
const std::string s = ss.str(); // must exist as long as sz is being used
const char *sz = s.c_str();
n and d are integers. Here is how you can convert integer to string:
std::string s;
std::stringstream out;
out << n << "/" << d;
s = out.str();
You could use a stringstream.
stringstream s;
s << n << "/" << d;
fracs.insert(make_pair((double)n/d, s.str()));
No one has suggested it yet but you can also take a look at boost::lexical_cast<>.
While this method is sometimes criticized because of performance issues, it might be ok in your situation, and it surely makes the code more readable.
Unlike in Java, in C++ there is no operator+ that explicitly converts a number to a string. What is usually done in C++ in cases like this is...
#include <sstream>
stringstream ss;
ss << n << '/' << d; // Just like you'd do with cout
string s = ss.str(); // Convert the stringstream to a string
I think sprintf(), which is a function used to send formatted data to strings, would be a much clearer way to do it. Just the way you would use printf, but with the c-style string type char* as a first(additional) argument:
char* temp;
sprint(temp, "%d/%d", n, d);
std::string g(temp);
You could check it out at http://www.cplusplus.com/reference/cstdio/sprintf/