Re: toUpper and pointer to a string
Neelesh Bodas schrieb:
On Sep 22, 10:45 pm, Daniel Kay <daniel-k...@arcor.de> wrote:
Neelesh Bodas schrieb:
On Sep 22, 9:31 pm, gaga <baronessfrostb...@gmail.com> wrote:
my function should accept a pointer to a string as its argument. and
it should convert each charater to an uppercase letter. I know what i
need to do, its just my syntax is all out of whack.
void strUpper (char *myStr) {
int i;
strcpy (*myStr);
char myCopy[100]; //sufficiently large
strcpy(myCopy, myStr);
Always a bad idea...
Completely Agreed. but I think there is always a need of writing this
kind of code. For example, the strUpper you suggested (or the OP tried
to write) cannot be used in the following case:
int main()
{
strToUpper("helloworld");
}
Worse, there is nothing that stops you from writing such a code (The
non-const nature of parameter doesn't hints at it though). In such a
case, probably creating a local variable to copy the argument is the
only option.
If somebody would force me to write a function in C (what I try to avoid
in any way), which will not modify the input string, I would start with
the following declaration:
void strToUpper(const char* in, char* out);
The user can decide to modify the original string:
char str1[] = "hello";
strToUpper(str1, str1);
Or the user can copy the result into a new string:
char str1[] = "hello";
char str2[sizeof(str1)] = { 0 };
strToUpper(str1, str2);
I hope this is true, since I didn't compile it... :-)
2. Better, use std::string class and std::transform. Something like
this:
void strUpper (string s)
{
string t;
transform(s.begin(), s.end(), back_inserter(t), (int(*)
(int))toupper);
}
This function will not change anything, unless the function retrieves a
pointer or even better a reference to a std::string.
Ok, one can have
string strUpper (const string& s); //returns the local variable t by
value
or
void strUpper(string& s); //no need of local variable, transform the
argument
The central idea was to suggest that std::string is much safer to use
than char*.
Ok, just wanted to make sure that uses copy/paste with that function and
wonders why the string isn't changed like the original poster intended
to do.
--
Cya,
Daniel