How does one simply make a mutator or setter for an array of strings? I have made a inspector or accessor but cant seem to figure out how to make a mutator.
much appreciated.
How does one simply make a mutator or setter for an array of strings? I have made a inspector or accessor but cant seem to figure out how to make a mutator.
much appreciated.
struct StringArray
{
char sArray[10][10];
void setString(char *s, int pos) {strcpy(sArray[pos], s);}
};
setString should change/set/mutate sArray by assigning s to element pos in sArray.
You need to use strcpy() to "assign" one C style string to another. You would need to be sure there is enough room in sArray[pos] to accomodate s in order to avoid a bug that might otherwise be difficult to spot.
You can change how you declare sArray.
Easy, you just return a reference from the indexing operator. Here's what I mean:
class int_array {
private:
int arr[10];
public:
// element accessor:
int operator[](int i) const { return arr[i]; };
// element mutator:
int& operator[](int i) { return arr[i]; };
};
And that's it, same for std::string
elements or anything else.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.