1

I'm trying to create a function that sorts strings, and I've made a function that I think should work, but the toupper() function doesn't seem to be having any effect. Is there something I am missing here?

void selectionSort(string array[], int size) {
    int startScan, minIndex;
    string minValue;

    for(startScan=0; startScan<(size-1); startScan++) {
        minIndex = startScan;
        minValue = array[startScan];

        for(int index=startScan+1; index<size; index++) {
            string word = array[index];
            toupper(word[0]);
            if(array[index] < minValue) {
                minValue = array[index];
                minIndex = index;
            }
        }
        array[minIndex] = array[startScan];
        array[startScan] = minValue;
    }
}
2
  • 1
    You're not assigning the value toupper() returns. Commented Feb 3, 2016 at 6:06
  • 1
    If you have a problem with toupper, why dump the entire sort function on the unsuspecting reader? Also, you probably shoukkd be using std::vector and std::sort in real code. Commented Feb 3, 2016 at 6:12

2 Answers 2

3
toupper(word[0]);

This statement calculates the value of the expression toupper(word[0]), and then throws the result away.

Change it to:

word[0] = toupper(word[0])
Sign up to request clarification or add additional context in comments.

Comments

2

You're not assigning the return value of the toupper() function. But anyway, it doesn't do, what you probably think it does (regardless, that word is not used afterwards): It will just capital one letter. What you probably want to do is to capitalize the whole word:

std::transform with toupper as a parameter can be used.

#include <string>
#include <algorithm>
void selectionSort(string array[], int size) {
  int startScan, minIndex;
  string minValue;

  for (startScan = 0; startScan<(size - 1); startScan++) {
    minIndex = startScan;
    minValue = array[startScan];

    for (int index = startScan + 1; index<size; index++) {
      string word = array[index];
      std::transform(word.begin(), word.end(), word.begin(), ::toupper);
      if (array[index] < minValue) {
        minValue = array[index];
        minIndex = index;
      }
    }
    array[minIndex] = array[startScan];
    array[startScan] = minValue;
  }
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.