Search code examples
c++fileloopslowercase

Convert to Lower and Hold in Str - C++


I'm trying to convert a string that I'm reading from a file to lowercase and hold the lowercase string in a separate string for comparison, but I want to keep the original string around for presentation, but I'm having some trouble:

ifstream file;
string name,
       lnStr,
       searchStr,
       lowerStr;
int lineNum = 0;
int strCount;

while(getline(file, lnStr))
    {
        lowerStr = lnStr;
        for(int i = 0; lowerStr[i] != '\0'; i++){
            lowerStr[i] = tolower(lowerStr[i]);
        }
        if(lowerStr.find(searchStr, 0) < lnStr.npos)
        {
            cout << setw(5) << ++lineNum << ":" << lnStr << endl;
            strCount++;
        }
    }

apparently I can't use sub[i] on strings, but it seems too much to hold it all in an array. Am I doing this the most efficiently? How can I get my lowercase string and original string separate?


Solution

  • There is no guarantee that lowerStr[i] will ever be 0 for any value of i.

        for(int i = 0; lowerStr[i] != '\0'; i++){
            lowerStr[i] = tolower(lowerStr[i]);
        }
    

    Try this:

    // UNTESTED
    for(int i = 0; i < lowerStr.size(); i++)
        lowerStr[i] = tolower(lowerStr[i]);
    

    Or, as Oli suggests:

    std::transform(lowerStr.begin(), lowerStr.end(), lowerStr.begin(), ::tolower);
    

    Ps. I can't test this fix for you because you didn't supply a complete test case. If you had, I would have.