0
#include <iostream>
#include <string>

using namespace std;

int main(){
    string str = "Gregory";
    int k = 0;

    for (k=0; str[k]!='\0';k++){
        if (str[k]>=65 && str[k]<=90)
        {
            str[k]+=32;
        }
    }

    cout << str << endl;
}

is this code right

Edited by WaltP: Added CODE Tags -- please use them

3
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by Narue
0

What are you trying to do with it? Also please use code tags when posting code. I would also change your for loop to

for (size_t i = 0; i < str.size(); i++)
{
    //...
}
0
#include <iostream>
#include <string>

using namespace std;

int main(){
    string str = "Gregory";
    int k = 0;

    for (k=0; str[k]!='\0';k++){
        if (str[k]>=65 && str[k]<=90)
        {
            str[k]+=32;
        }
    }

    cout << str << endl;
}

is this code right

No. Ignoring your assumptions about the character set, std::string is not required to be null terminated except through the c_str() member function. This would be "correct", provided certain assumptions hold about the character set:

#include <iostream>
#include <string>

int main()
{
    std::string str = "Gregory";

    for (int k = 0; k != str.size(); k++) {
        if (str[k] >= 65 && str[k] <= 90)
            str[k] += 32;
    }

    std::cout << str << '\n';
}

This would be more correct, because the task of converting to lower case is handled by the standard library:

#include <cctype>
#include <iostream>
#include <string>

int main()
{
    std::string str = "Gregory";

    for (int k = 0; k != str.size(); k++)
        str[k] = std::tolower((unsigned char)str[k]);

    std::cout << str << '\n';
}

And this is correct in the presence of locales, so even characters outside of the basic character set should be correctly converted:

#include <iostream>
#include <locale>
#include <string>

int main()
{
    std::string str = "Gregory";
    std::locale here("");

    for (int k = 0; k != str.size(); k++)
        str[k] = std::tolower(str[k], here);

    std::cout.imbue(here);
    std::cout << str << L'\n';
}

To be strictly correct the code would need to account for multibyte characters, though getting into localization at that level begins to get muddy. Examples are rarely so thorough due to that, though in practice your code should take internationalization into account. ;)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.