+ 1

Convert array of chars into string using c++.

I have coded a random password generator, but I would like to save the password as a string. Is it possible to convert an array of chars into a string in c++? Thanks.

9th Nov 2016, 2:48 PM
NICKALL [EP]
NICKALL [EP] - avatar
5 Answers
+ 4
char a[] = "sololearn"; string s = string(a); cout<<s;
9th Nov 2016, 3:23 PM
kamal joshi
kamal joshi - avatar
+ 3
Yes, array of characters is a string with ending \0. try to put \0 in last array index and that can store in string variable.
9th Nov 2016, 3:04 PM
Aditya kumar pandey
Aditya kumar pandey - avatar
+ 3
this will work even with uninitialized char array. After you have stored all the char in the array, you just need to write this code at the end to convert it into string.
9th Nov 2016, 4:15 PM
kamal joshi
kamal joshi - avatar
+ 2
Works like a charm thanks sooo much!
9th Nov 2016, 5:05 PM
NICKALL [EP]
NICKALL [EP] - avatar
+ 1
@kamal joshi Your code works great. But if i used an array for 'acceptable chars' and a for loop to produce an array that holds random numbers each time you run the code, using srand(time(0)) and rand(), how do I convert that array that wasn't initialized into a string. Or is that even possible?
9th Nov 2016, 3:56 PM
NICKALL [EP]
NICKALL [EP] - avatar