2

Basically my task is having to sort a bunch of strings of variable length ignoring case. I understand there is a function strcasecmp() that compares cstrings, but doesn't work on strings. Right now I'm using getline() for strings so I can just read in the strings one line at a time. I add these to a vector of strings, then convert to cstrings for each call of strcasecmp(). Instead of having to convert each string to a cstring before comparing with strcasecmp(), I was wondering if there was a way I could use cin.getline() for cstrings without having a predefined char array size. Or, would the best solution be to just read in string, convert to cstring, store in vector, then sort?

2 Answers 2

2

I assume by "convert to cstring" you mean using the c_str() member of string. If that is the case, in most implementation that isn't really a conversion, it's just an accessor. The difference is only important if you are worried about performance (which it sounds like you are). Internally std::strings are (pretty much always, but technically do not have to be) represented as a "cstring". The class takes care of managing it's size for you, but it's just a dynamically allocated cstring underneath.

So, to directly answer: You have to specify the size of the array when using cin.getline. If you don't want to specify a size, then use getline and std::string. There's nothing wrong with that approach.

2
  • hmm wouldn't it slow down the program significantly to have that extra line of string.c_str()?
    – zebraman
    Apr 2, 2010 at 23:25
  • 3
    @zebraman: That's probably least of your concerns. Profile and see what proportion of time it takes.
    – UncleBens
    Apr 2, 2010 at 23:29
0

C++ is pretty efficient on its own. Unless you have a truly proven need to do otherwise, let it do its thing.

#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
#include <cstring>

using namespace std;

bool cmp(string a, string b)
{
    return(strcasecmp(a.c_str(), b.c_str()) < 0);
}  


int main(int argc, char *argv[])
{
    vector<string> strArr;

    //too lazy to test with getline(cin, str);

    strArr.push_back("aaaaa");
    strArr.push_back("AAAAA");
    strArr.push_back("ababab");
    strArr.push_back("bababa");
    strArr.push_back("abcabc");
    strArr.push_back("cbacba");
    strArr.push_back("AbCdEf");
    strArr.push_back("aBcDeF");
    strArr.push_back("  whatever");

    sort(strArr.begin(), strArr.end(), cmp);

    copy(strArr.begin(), strArr.end(), ostream_iterator<string>(cout, " \n"));

    return(0);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.