1

Playing with some functions and my computer/NetBeans cannot seem to run my code, even though it can be run in different compilers. Here's my function (keep in mind this isn't my whole project I do have an int main()):

#include <iostream>
#include <iomanip>
#include <string>
#include <iterator>
#include <cstdlib>
#include <ctime>
#include <windows.h>
using namespace std;
void convert (string& s){ //Creating a function that makes a variable lower case
    for(int i=0; i<s.length(); i++){ 
        s[i] = tolower(s[i]); //tolower lets me change to lower case
    }
}

The error I'm getting is: "cannot resolve identifier length". if you need to see my whole project please ask, I don't mind, just think its a waste of time if it doesn't matter. I'm using NetBeans 8.2, thanks in advance

Aidan Christopher
  • 161
  • 2
  • 2
  • 10

2 Answers2

1

You can try size() instead of length() . For string in C++ there's no notable difference between them but size() is used in other STL containers like map, vector etc. too. So generally, people use size() function.

Usage is same like length(), i < s.size()

1

It looks as though the implementation of std::string has omitted the function length(); BTW, it does not return int, so you should get a warning ticket for that. In future, please post a complete program, including main().

Workaround the old way;

#include <string>

void convert(std::string& s) { //Creating a function that makes a variable lower case
    const size_t sz = s.size();

    for (size_t i = 0; i<sz; ++i) {
        s[i] = tolower(s[i]); //tolower lets me change to lower case
    }
}

int main() {
    std::string s("AbCdEf");
    convert(s);
    return 0;
}

Newfangled way...

#include <string>

void convert(std::string& s) { //Creating a function that makes a variable lower case
    for (char &ch : s) {
        ch = tolower(ch); //tolower lets me change to lower case
    }
}

int main() {
    std::string s("AbCdEf");
    convert(s);
    return 0;
}

Even newfangleder way...

#include <algorithm>

void convert(std::string& s) { //Creating a function that makes a variable lower case
       std::transform(std::begin(s), std::end(s), std::begin(s), ::tolower);
}
Jive Dadson
  • 16,680
  • 9
  • 52
  • 65