#include <iostream>
#include <string>
usingnamespace std;
void reverse(string& str);
int main()
{
cout << "Enter a string: ";
string s;
getline(cin, s);
reverse(s);
cin.ignore();
cin.get();
return 0;
}
void reverse(string& str)
{
constchar* cstr = str.c_str();
for (int i = strlen(cstr); i > 0; --i)
{
strcpy(str, cstr[i]);
}
}
This was meant to reverse strings.
But my question pertains to strings and c-strings in general. If someone can explain to me in-depth and with examples, their relationships and how they work when passed to functions I would appreciate it. I've read the entire chapter in the course I'm learning from and I've already searched online, but no one has given a full explanation, just patchwork codes.
my question pertains to strings and c-strings in general. If someone can explain to me in-depth
A C-string is simply an array of chars terminated by a null character.
When passed to a function, it is always passed to the function as a pointer.
1 2 3 4 5 6
char cstr[10]; // Holds up to 9 chars + terminating null
void somefunc (char * str); // Function declaration
somefunc (cstr); // Pass the array to somefunc
somefunc (&cstr[2]); // Pass array starting with 3rd char
std::string on the other hand is a C++ class. The std::string class maintains internal storage for the contents of the string. std::string provides semantics to retrieve and assign specific characters, concatenate another string, etc. std:string can be passed to a function by value (a copy is made), by reference, or via a pointer.
1 2 3 4 5 6 7 8
std::string str ("some text");
void func1 (std::string str); // Accepts str by value (a copy)
void func2 (std::string & str); // accepts str by reference
void func3 (std::string * str); // Accepts a pointer to a string object
func1 (str); // pass by value
func2 (str); // pass by reference
func3 (&str); // pass a pointer to the string object.
Note that taking the address of a string returns the address of the string object, not the address of the internal representation of the string. If you want to pass a std:;string to a C function, then you use the c_str() method.
How would you make this work? I have encountered exercises where I was supposed to pass strings into a function that will do c-string operations on it. Can this work directly or do I have to convert the string into a char array inside the function and then work on it?