how would i convert a char array, ie. address[256] into a string?
how would i convert a char array, ie. address[256] into a string?
Code:#include <string> #include <iostream> #include <ostream> int main() { char chars [] = "Did you try?"; std::string example; example = chars; std::cout << example.c_str() << std::endl; }
Code:char charAddress[] = "123 Maple Way"; string strAddress = charAddress; cout<<strAddress<<endl;
that would convert a char array of size 256 where array[i] is an element to a string, ie. say i have an address which is made up of 20 chars will that convert it to a string?
If the data in the character array is properly NULL terminated, then you can simply assign the character array to the string container object and it will be converted (as has been demonstrated). If the first 20 characters out of that 256 length array contain data (with the 21st character being a NULL), then the resulting string will contain 20 characters.
"Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
-Christopher Hitchens
>> std::cout << example.c_str() << std::endl;
No need for c_str() there.
say for example i have a text file, and im using I/O stream, my file is constantly being update so i dont know how many lines there will be, is there a way of getting the num of lines?
I know, just showing how you would go about converting a string back to a c style char arrayNo need for c_str() there.
>> is there a way of getting the num of lines?
You would have to make a pass through the file all the way through to count the number of lines, then go back to the beginning to read it again. However, if you use C++ tools like vector and string then you rarely need to know the exact number of lines because those things grow automatically and you can just loop through the file one line at a time until you reach the end. This would be the preferred approach.