Good job. You just need to apply some careful formatting to your code. (If you do this from the very start it will be much easier for you to reason about your code. You'll notice that everyone who responded here posted nicely formatted code which is easy to read and understand. If you do the same to your code you'll find that you struggle less with it.
Use whitespace liberally. Things that are subordinate to another thing need to be indented further. For example:
1 2 3 4 5 6 7 8 9 10
|
int myfunction() // no indent -- the function is at the file level
{
// everything inside the function gets an indent, since it is all inside the function
if (fooey())
barf(); // again, we only barf if fooey happens -- so we indent a little more on this line than the if's line
return 9; // since this is not dependent on fooey(), but it is on myfunction(), we return to the function body indent distance
}
| |
Notice also how I put the open and close braces on the same line, and how there is a blank line following the closing brace. While style is a matter of taste and debate, in
your particular case this particular form is a good idea. It will help you to uncrowd your program and manage indenting properly. It will also get you higher marks from your professor. (Honest!)
Well then, without further ado, here is your program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
#include <cstring>
#include <iostream>
using namespace std;
void ChangeCase(char word[])
{
for(size_t i = 0; i < strlen(word); i++)
{
if(isupper(word[i]))
word[i] = tolower(word[i]);
else
if(islower(word[i]))
word[i] = toupper(word[i]);
}
}
int main()
{
char word[20] = "C++ ProGram";
ChangeCase(word);
cout << word;
return 0;
}
| |
I made two changes.
Line 1: this one was necessary, since you use
strlen() on line 7. Whenever you use a function it is a good idea to make sure you have its header #included at the top of your code. You can find out what header is necessary just by googling something like "c++ strlen". Your top result will usually point right back to this site. The file to #include is listed on the top, right side of the page.
You don't technically need to use
strlen(). Line 7 could read:
7 for (size_t i = 0; word[i] != '\0'; i++)
Every c-string ends with the zero character (
'\0'), so you can just stop when you find it.
Line 7: this change was not necessary, but you might as well learn it anyway. ;-)
Using
int as your loop counter variable
i's type is fine, but it causes compiler warnings when it doesn't match the signedness of
strlen()'s result. If you use the
same type for the variable as returned by
strlen(), then there is no sign mismatch and the compiler doesn't spew verbiage at you.
Hope this helps.