Convert from char array to string variable

2211 views c++
4

In my C++ program I am to read from a file one character at a time and stop when the loop reaches a space (this would indicate the end of a single word). Then, I want to assign the contents of the char array to a string variable.

I know I can read one word at a time from the file, however for my assignment this is not a suitable solution.

My difficulty is converting from char array to a string variable .

answered question

std::string(arr)

1 Answer

10

std::string actually has a constructor that takes a C-style string! As long as you make sure your char array is null terminated, you can do:

char myArr[]; //Make sure it's null terminated!
std::string myString(myArr);

posted this

Have an answer?

JD

Please login first before posting an answer.