Search code examples
c++stringfilevectorc++17

Is there a way to use a tolower() like function on a vector<string> variable in C++?


I'm trying to load and sort a file alphabetically. To make this easier, I have to convert the characters to lowercase.

Now, do I have to do this character-by-character as I read it into a string array (because tolower() only accepts characters), or can I somehow use it with a vector<string> container?

Here's the code:

#include <iostream>
#include <fstream>
#include <cstring>
#include <vector>

using namespace std;

int main() {

   ifstream file("phoneNumbers.txt");
   vector<string> wordStream;
   int i = 0;

    if (file.fail()) {
        cout << "Couldn't open file!";
        return 1;
    }

    while(file>>wordStream[i]) {
        wordStream[i] = tolower(wordStream[i]);
        ++i;
    }
}

Newbie question, I know.

I already tried the std::transform() function that someone recommended on StackOverflow, but still it didn't work.


Solution

  • Your code has two problems, tolower doesn't work on strings, and your vector has a size of zero so wordStream[i] is an error for any value of i. Here's the code fixed of those errors

    string temp;
    while (file >> temp) { // read to a temporary string
        // convert string to lower case
        std::transform(temp.begin(), temp.end(), temp.begin(), tolower);
        // add temporary string to vector
        wordStream.push_back(temp);
    }