0

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 
4
  • 1
    Not a very well-formed question -- what have you tried? And what didn't work about it? Commented Dec 8, 2014 at 19:11
  • 1
    I don't think that edit by Houssem should have been approved. Changed string to String and removed a potential example. Commented Dec 8, 2014 at 19:35
  • @crashmstr he is newbye and should learn write correctly and not to put non-informative lines Commented Dec 9, 2014 at 13:23
  • @HoussemBdr and when is a string String? Your changes were not significantly better in my opinion, and I would not have approved them had I seen them before they took place. Commented Dec 9, 2014 at 13:37

2 Answers 2

3

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";
Sign up to request clarification or add additional context in comments.

Comments

1

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".
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.