Search code examples
c++strcmpstrcpy

strcpy and strcmp, what am I doing wrong?


User should enter a few strings and input space as string when he is done. Code should return longest and shortest word entered.

strcmp always returns -1... what am i doing wrong?

#include <iostream>
#include <cstring>
using namespace std;
int main() {
    char S[100][20];
    int I = 0;
    do {
            cout << "Enter text:" << endl;
            cin.getline(S[I],100);
    } while (I < 19 && strcmp(S[I++],""));
    char Max[100], Min[100];
    strcpy(Max, S[0]);
    strcpy(Min, S[0]);
    for (int J = 1; J < I; J++) {
        if (strcmp(S[J], Max) == 1)
            strcpy(Max, S[J]);
        if (strcmp(S[J], Min) == -1)
            strcpy(Min, S[J]);
    }
    cout << "Max = " << Max << endl;
    cout << "Min = " << Min << endl;
    system("pause");
    return 0;
}

Solution

  • So, a couple of things:

    • variables should be lowercase;
    • you are defining your array of string with wrong length (should be s[20][100]);
    • in your while cycle, you should go 'till i < 20;
    • the last string in your array will always be the empty string (hence: s_min will be always empty);
    • strcmp compares strings, it doesn't tell you which one is the longest. You should use strlen for that...

    Here the working code:

    #include <iostream>
    #include <cstring>
    using namespace std;
    
    int main() {
      char s[20][100];
      int i = 0;
      do {
        cout << "Enter text:" << endl;
        cin.getline(s[i], 100);
      } while (i < 20 && strcmp(s[i++],""));
    
      char s_max[100], s_min[100];
      strcpy(s_max, s[0]);
      strcpy(s_min, s[0]);
      for (int j = 1; j < i-1; j++) {
        if (strlen(s[j]) > strlen(s_max))
          strcpy(s_max, s[j]);
        if (strlen(s[j]) < strlen(s_min))
          strcpy(s_min, s[j]);
      }
    
      cout << "Max = " << s_max << endl;
      cout << "Min = " << s_min << endl;
      return 0;
    }