Jay KS
Jay KS

Reputation: 1

How to copy an array of characters to a string C++

I am writing a function that takes in a string through pass by reference and an array of characters and the size of the array. The string already has characters in it. I am trying to erase the characters in the string and copy the characters from the array. I tried setting up a for loop to copy, but it doesn't work if the string is too small or too big. I can't use strcopy in this function. Need some guidance.

void functionname(string &first, char arr[], int size) {

int i;

    (for i = 0; i < size; i++) {
    first[i] = arr[i];
    }

}

Upvotes: 0

Views: 568

Answers (4)

Ryan Henning
Ryan Henning

Reputation: 126

string has a constructor that copies a character array and takes a count. This will work no matter what contents are inside the arr array, even embedded null characters.

void functionname(string &first, char arr[], int size) {

    first = string(arr, size);

}

Again, the contents of arr are copied into the string, you don't need to keep arr around after this if you don't need it anymore.

Upvotes: 0

Paul Rooney
Paul Rooney

Reputation: 21609

The below works as std::string overrides the assignment operator (=) for char* to allow direct assignment to the string from a character pointer.

#include <iostream>
#include <string>
#include <cstring>

using namespace std;

void functionname(string &first, char arr[], int size) 
{
    first = arr;
}

int main()
{
    std::string x = "mystring";
    char buff[x.length()];
    strcpy(buff, "other");

    cout << x << endl;
    functionname(x, buff, x.length());

    cout << x << endl;

    return 0;
}

Upvotes: 1

uuu777
uuu777

Reputation: 901

std::string has function to do it first.assign(arr, size)

Upvotes: 2

thor
thor

Reputation: 22460

You can use std::string's default assignment operator = and simply do

first = arr;

Upvotes: 2

Related Questions