A C Program to sort two strings

Lazaro Claiborn 0 Tallied Votes 226 Views Share

Here is just a simple program to sort two strings inputted from the user entered on the command line.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define MAXBUFF 80
#define TRASHSIZE 200

/* Gets extra junk off stdin of size of TRASHSIZE */
void getJunk(void) {
 char junk[TRASHSIZE];
 fgets(junk,TRASHSIZE,stdin);
}

/* Converts upper case letters to lower case */
void toLower(char *str) {
 int len = strlen(str), i;
 for (i=0;i<len;i++)
  if (str[i] >= 65 && str[i] <= 90) 
   name[i] += 32;
}

/* Has the same effect as strcmp but I just decided to write my own and save compiler time */
int cmpstr(char *, char*);

int main() {
 char str1[MAXBUFF], str2[MAXBUFF];
 int len1, len2, i;

/* Get the two strings from the user */
 printf("Please enter a string: ");
 scanf("%s", str1);

 getJunk(); 

 printf("Please enter another string: ");
 scanf("%s", str2);

/* Convert both string to lowercase before comparing */
 toLower(str1);
 toLower(str2);

 i = cmpstr(str1, str2);

 if (!i)
  printf("%s is equal to %s", str1, str2);
 else if (i==1)
  printf("%s %s", str1, str2);
 else if (i==2)
  printf("%s %s", str2, str1);

 system("pause");
 return 0;
}

int cmpstr(char *str1, char *str2) {
 int len1, len2, i;
 
 len1 = strlen(str1);
 len2 = strlen(str2);

 for (i=0;i<len1 && i<len2;i++) {
  if (str1[i] < str2[i])
   return 1;
  else if (str[i] > str2[i])
   return 2;
 }
 return 0;
}

Dani AI

Generated

Quick expert note: the snippet is a useful learning exercise, but beyond the simple typos that (and earlier @~s.o.s~) flagged, there are a few design and portability problems worth fixing to make the program robust and correct.

Input handling

  • Avoid scanf("%s", ...) for general input: it stops at whitespace and can overflow buffers. Use line-oriented input (fgets) into a fixed-size buffer, check the return value, strip a trailing newline, and detect/truncate overly long lines instead of relying on a fragile getJunk() hack.

Case conversion and comparison

  • Do not hard-code ASCII values (65/90). Use <ctype.h> helpers and cast to unsigned char when calling them (e.g. pass (unsigned char)c to tolower) to avoid undefined behavior on platforms where char is signed.
  • Prefer existing, tested functions rather than rolling your own: use strcasecmp/strncasecmp on POSIX or _stricmp on Windows for case-insensitive compares, or strcoll when locale-aware collation is required. If a custom comparator is necessary, make it follow strcmp semantics (negative if str1 < str2, zero if equal, positive if str1 > str2) and treat equal prefixes by comparing lengths (shorter string is less).

Types, safety and style

  • Use size_t for lengths and indices returned by strlen.
  • Always check return values (I/O, library calls).
  • Remove non-portable bits like system("pause") and avoid magic constants like TRASHSIZE; prefer clear, bounded logic or expand buffers when needed.
  • If the program must handle human languages or UTF-8, bytewise comparison is not sufficient — use proper Unicode-aware libraries.

Summary checklist

  • Fix the simple typos pointed out by .
  • Replace scanf+getJunk with fgets + newline trimming.
  • Use tolower/isupper with unsigned char casts.
  • Rely on standard case-insensitive or locale-aware compares, or implement full strcmp-style return semantics and length tie-breaking.
  • Use safe types (size_t) and check all returns.
John A 1,896 Vampirical Lurker Team Colleague

>Has the same effect as strcmp but I just decided to write my own and save compiler time
Yes, it definitely saves a lot of compiler time when the thing doesn't even get to the linking stage. You've made one or two corrections, but the snippet still leaves much lacking, and overall a terrible piece of code.

The first is here:

/* Converts upper case letters to lower case */
void toLower(char *str) {
 int len = strlen(str), i;
 for (i=0;i<len;i++)
  if (str[i] >= 65 && str[i] <= 90) 
   name[i] += 32; /* 'name' has never been declared; change this to 'str' */
}

You've got another typo in your cmpstr function:

int cmpstr(char *str1, char *str2) {
 int len1, len2, i;
 
 len1 = strlen(str1);
 len2 = strlen(str2);

 for (i=0;i<len1 && i<len2;i++) {
  if (str1[i] < str2[i])
   return 1;
  else if (str[i] > str2[i]) /* change 'str' to 'str1' */
   return 2;
 }
 return 0;
}

Like ~s.o.s~ already stated in the previous thread, cmpstr should return the difference between the 2 strings instead of simply a 1 or 2, so as to make it nearly identical to the original strcmp funcition.

Secondly, your getJunk() function is very crude and limited -- what happens if there's more than 1 newline in the input buffer, or if there's nothing in there at all? It works in this case, but it should work in most cases. A better version can be seen here.

In fact, instead of using scanf for your input, you should rely purely on fgets() for your input. It's a much better input method because it does not have the constant problem of leaving behind newlines in the buffer. Also see this for even better detail on why scanf is bad. Here is how to do input properly with fgets:
http://www.daniweb.com/tutorials/tutorial45806.html

There's many more problems with your code, but hopefully this will give you a basic idea of what's wrong with your code.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.