Reputation: 152
Can somebody help me in converting some elements of char array[]
into String
.
I'm still learning strings.
char input[40] = "save filename.txt";
int j;
string check;
for (int i = 0; input[i] != '\0'; i++)
{
if (input[i] == ' ')
{
j = i+1;
break;
}
}
int index;
for (int m = 0; arr[j] != '\0'; m++)
{
check[m] = arr[j];
j++;
index = m; //to store '\0' in string ??
}
check[index] = '\0';
cout << check; //now, String should output 'filename.txt" only
Upvotes: 0
Views: 906
Reputation: 15524
The ctor of std::string
has some useful overloads for constructing a string from a char
array. The overloads are about equivalent to the following when used in practice:
Taking a pointer to constant char
, i.e. a null-terminated C-string.
string(const char* s);
The char
array must be terminated with the null character, e.g. {'t', 'e', 's', 't', '\0'}
. String literals in C++ is always automatically null-terminated, e.g. "abc"
returns a const char[4]
with elements {'a', 'b', 'c', '\0'}
.
Taking a pointer to constant char
and specified number of characters to copy.
string(const char* s, size_type count);
Same as above but only count
number of characters will be copied from the char
array argument. The passed char
array does not necessarily have to be null-terminated.
Taking 2 iterators.
string(InputIt first, InputIt last);
Can be used to construct a string from a range of characters, e.g.
const char[] c = "character array";
std::string s{std::next(std::begin(c), 10), std::end(c)}; // s == "array".
Upvotes: 1
Reputation: 2509
The string class has a constructor that takes a NULL-terminated C-string:
char arr[ ] = "filename.txt";
string str(arr);
// You can also assign directly to a string.
str = "filename.txt";
Upvotes: 3