-1

i was extracting lowercase and uppercase characters from a string . then print those uppercase and lowercase string in sorted order in .to sort the string i used std::sort function .but it's not working.

here is my code

#include <bits/stdc++.h>

using namespace std;
int main() {
//std::ios::sync_with_stdio(false);
char str[1005];
char low[1005];
char upr[1005];
int n;
int t;
cin>>t;
while(t--)
    {
    cin>>n;
    cin>>str;
    low[0]='\0';
    upr[0]='\0';
    int i=0,j=0,k=0;
    while(i<n)
        {
        (str[i]>='A' && str[i]<='Z') ? (upr[j]=str[i],++j) : (low[k]=str[i],++k) ;
        ++i;
        }
    low[j]='\0';
    upr[k]='\0';
    cout<<"lowercase="<<low<<'\n';
    cout<<"uppercase="<<upr<<'\n';
    sort(low,low+j);
    sort(upr,upr+k);
    cout<<"lowercase="<<low<<'\n';
    cout<<"uppercase="<<upr<<'\n';
    }
return 0;
}

test case:

1    // number of test cases
15   // length of string
abHJUdjKIpwlaKm

output:

lowercase=abdjpw    //before sorting
uppercase=HJUKIK    //before sorting
lowercase=abdjpw     //after sorting
uppercase=          //after sorting

after sorting uppercase string don't even print.

Nishant sharma
  • 116
  • 1
  • 11
  • 5
    `(str[i]>='A' && str[i]<='Z') ? (upr[j]=str[i],++j) : (low[k]=str[i],++k)` <-- Just use a dang `if` block. – cdhowie Jun 06 '17 at 15:05
  • 5
    Look at the names of the variables you're using for indexing until the answer appears. Then consider how much time you could have saved by using more informative names. – molbdnilo Jun 06 '17 at 15:09
  • 3
    For an obfuscated C++ contest, this is not quite incomprehensible enough. But for normal code, this is plain awful in terms of clarity. Why all the indexing instead of a few `std::string`s? Why the horrible ternary operator? Why single-letter variables (which actually caused the whole issue)? And [don't `#include `](https://stackoverflow.com/q/31816095/1782465). – Angew is no longer proud of SO Jun 06 '17 at 15:23

3 Answers3

4

You have a bug with indexes, fix:

low[k] = '\0';
upr[j] = '\0';
cout << "lowercase=" << low << '\n';
cout << "uppercase=" << upr << '\n';
sort(low, low + k);
sort(upr, upr + j);
cout << "lowercase=" << low << '\n';
cout << "uppercase=" << upr << '\n';

Exchanged k and j in this snippet.

Yuki
  • 3,857
  • 5
  • 25
  • 43
4

Better variable names would help. Try replacing j and k with something more descriptive like lowIndex and uprIndex. Then you should see the problem.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
Mike
  • 3,462
  • 22
  • 25
2

I noticed you were using j variable for uppercase and k for lowercase in the while loop then proceeded to do the opposite later. Was this intentional? Wondering if that's causing a bug.

John
  • 31
  • 3