GIDForums  

Go Back   GIDForums > Computer Programming Forums > C Programming Language
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 18-Nov-2004, 22:15
doc_watson2007 doc_watson2007 is offline
New Member
 
Join Date: Oct 2004
Posts: 7
doc_watson2007 is on a distinguished road
Talking

sorting string w/strcmp


I am working on another project for school, I need to sort and print a new list.
I have to use the strcmp to help with the sorting and use #define strings 7.
CPP / C++ / C Code:
#include <stdio.h>
#include <string.h>

	int main(void)
{
	int i;
	char str[7];
	    
	printf ("Please enter a String: press <return>: ");
    scanf("%s",str);
	printf(" %c \n",str[0]);
	printf(" %c \n",str[1]);
	printf(" %c \n",str[2]);
	printf(" %c \n",str[3]);
	printf(" %c \n",str[4]);
	printf(" %c \n",str[5]);
	printf(" %c \n",str[6]);

	i = strcmp(&str[0], &str[1]);
	if(!i)
        printf("The strings are equal.\n");
	else
		if (i<0)
			printf("%c\n", str[0]);
		else
			printf("%c\n", str[1]);
	
    return 0;
 }
  #2  
Old 19-Nov-2004, 03:58
WaltP's Avatar
WaltP WaltP is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Midwest US
Posts: 3,258
WaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to all
Quote:
Originally Posted by doc_watson2007
I am working on another project for school, I need to sort and print a new list.
I have to use the strcmp to help with the sorting and use #define strings 7.
CPP / C++ / C Code:
#include <stdio.h>
#include <string.h>

	int main(void)
{
	int i;
	char str[7];
	    
	printf ("Please enter a String: press <return>: ");
    scanf("%s",str);
	printf(" %c \n",str[0]);
	printf(" %c \n",str[1]);
	printf(" %c \n",str[2]);
	printf(" %c \n",str[3]);
	printf(" %c \n",str[4]);
	printf(" %c \n",str[5]);
	printf(" %c \n",str[6]);

	i = strcmp(&str[0], &str[1]);
	if(!i)
        printf("The strings are equal.\n");
	else
		if (i<0)
			printf("%c\n", str[0]);
		else
			printf("%c\n", str[1]);
	
    return 0;
 }

The first thing you need to do is read in a bunch of strings to sort. Read them into an array of char*'s. Get that done first, and output the strings.

Next, create the sort function and pass the address of this array to the function.

From there you should have it...
__________________

Got a cough? Go home tonight and eat a whole box of Ex-Lax. Tomorrow, you'll be afraid to cough.
-- Pearl Williams
  #3  
Old 20-Nov-2004, 01:09
doc_watson2007 doc_watson2007 is offline
New Member
 
Join Date: Oct 2004
Posts: 7
doc_watson2007 is on a distinguished road
Question

Quote:
Originally Posted by WaltP
The first thing you need to do is read in a bunch of strings to sort. Read them into an array of char*'s. Get that done first, and output the strings.

Next, create the sort function and pass the address of this array to the function.

From there you should have it...

This is better wouldn't you say?
Now I need to go to the Next. MAyB or Mayb NoT
CPP / C++ / C Code:
#include <stdio.h>
#include <string.h>
#define N_STRINGS 7

	int main(void)
{
	int i;
	int j; 
	int k; 
	char str[N_STRINGS];

	/* Fill array with zero's */
    for (k = 0; k < N_STRINGS; k++)
		str[k] = 0;
    {
        printf("\nPlease enter a strings and press <return>:  ");
        scanf(" %s",str);
    }
	/* Prints the list before it is sorted */
    printf("\nHere is the list before sort:\n\n");
    for (i = 0; i < N_STRINGS; i++)
	{
        printf(" %c\n", str[i]);

		for (j = i + 1; j < N_STRINGS; ++j);
            }
	/* Print the list after it is sorted */

	int sort;

	printf("\nHere is the list after sort:\n\n");
    
		
return 0;
  #4  
Old 20-Nov-2004, 03:59
nkhambal nkhambal is offline
Regular Member
 
Join Date: Jul 2004
Location: CA USA
Posts: 313
nkhambal is a jewel in the roughnkhambal is a jewel in the rough
Hi,

First you need to understand what a string means in C. In C strings are nothing but collection of chars or simply a character array. So your following declaration
CPP / C++ / C Code:
char str[N_STRINGS];
is nothing but one string. Here let me give you an example. Say I want to store a word John in char array str. This is how it is actually stored in str[].

str[0]='J'
str[1]='o'
str[2]='h'
str[3]='n'
str[4]='\0'


here '\0' marks the end of the string. Many library functions (strlen() for e.g.)that operate on strings (char arrays), use this special character (also called as NULL) to mark the end of the string. So you need to make sure you always allocate one extra character space in your char array for NULL terminator. Else your string reading function may fail or give unexpected results. Fortunately, to make our life easier when you read in a string using either scanf(),fscanf() or sscanf() using "%s" operator, a NULL terminator is automatically added at the end of the string.

Now coming back to your program.

You need to compare strings and not each characters in the strings.

First of all you need to define storage to store your strings i.e. char arrays.
CPP / C++ / C Code:
char str[7][SIZE]; 

You have defined a 7 storage locations to store the strings, each of the size "SIZE".

Next you need to read in few string from user input. here is one example.

CPP / C++ / C Code:
int i;
for (i=0;i<7;i++)
{
printf("Enter a string %d of size less than equal to %d: ",i,SIZE-1);
scanf("%s",str[i]);
}


Now that you have your 7 strings you need to start comparing them using strcmp() function which takes 2 strings, string1 and string2, as arguments and returns less than 0, equal to 0 or greater than 0 if string1 is less than,equal to or greater than string2.

you can use for loop to sort the string as follows

CPP / C++ / C Code:

int j;
char temp[SIZE];

for (i=0;i<7;i++)
{
   for (j=i+1;j<7;j++)
   {
      if (strcmp(str[i],str[j])>0)
       {
         strcpy(temp,str[i]);
         strcpy(str[i],str[j]);
         strcpy(str[j],temp);
        }
    }
}


Now you have sorted all the strings in ascending order. Now all you have to do is print it.
CPP / C++ / C Code:
printf("\nSorted strings are:\n);
for (i=0;i<7;i++)
{
printf("String %d : %s\n ",i,str[i]);
}

Following is what your program output will look like.

Quote:
Enter a string 0 of size less than equal to 7: john
Enter a string 1 of size less than equal to 7: david
Enter a string 2 of size less than equal to 7: walter
Enter a string 3 of size less than equal to 7: mike
Enter a string 4 of size less than equal to 7: kelly
Enter a string 5 of size less than equal to 7: jessica
Enter a string 6 of size less than equal to 7: nick

Sorted strings are:
String 0 : david
String 1 : jessica
String 2 : john
String 3 : kelly
String 4 : mike
String 5 : nick
String 6 : walter

I hope its clear enough to understand. Good luck.
  #5  
Old 20-Nov-2004, 10:17
WaltP's Avatar
WaltP WaltP is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Midwest US
Posts: 3,258
WaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to all
nkhambal's explanation is very good. A little too complete to my way of thinking , but very good none-the-less.
Quote:
Originally Posted by doc_watson2007
This is better wouldn't you say?
Now I need to go to the Next. MAyB or Mayb NoT
CPP / C++ / C Code:
 1#include <stdio.h>
 2#include <string.h>
 3#define N_STRINGS 7
 4
 5	int main(void)
 6{
 7	int i;
 8	int j; 
 9	int k; 
10	char str[N_STRINGS];
11
12	/* Fill array with zero's */
13    for (k = 0; k < N_STRINGS; k++)
14		str[k] = 0;
15    {
16        printf("\nPlease enter a strings and press <return>:  ");
17        scanf(" %s",str);
18    }
19	/* Prints the list before it is sorted */
20    printf("\nHere is the list before sort:\n\n");
21    for (i = 0; i < N_STRINGS; i++)
22	{
23        printf(" %c\n", str[i]);
24
25		for (j = i + 1; j < N_STRINGS; ++j);
26            }
27	/* Print the list after it is sorted */
28
29	int sort;
30
31	printf("\nHere is the list after sort:\n\n");
32    
33		
34return 0;
Nope. You've defined 1 string of size N_STRINGS (line 10)
Then you put zeros in that string (line 13/14) which is unnecessary
You the start a block (15) read 1 string (16/17) and end the block (18). So you read one and only one string
You now print each character of the string entered (20-23) and start a loop that does nothing but change j from your current loop counter+1 to 7 (24)

To define multiple strings, you need
CPP / C++ / C Code:
char str[N_STRINGS][SIZE_STRINGS];
where SIZE_STRINGS is the length of each string.

Also, most here discourage the use of scanf() and recommend fgets() because of the flaky way scanf() works. It requires an extra line of programming but it will not mess up your input stram like scanf() does.
CPP / C++ / C Code:
fgets(str[i], SIZE_STRING, stdio);
if (str[i][strlen(str[i]) - 1] == '\n') str[i][strlen(str[i]) -1 ] == '\0'
I know it looks convoluted, but what it's saying is
1) if the last character ([i]strlen(str) - 1) of the string str
2) is a return '\n'
3) change it to NULL '\0'

The easiest way to find out if you did it correctly is to actually run the program. You'll get your answer faster than posting here and waiting hours for a response. Then if the code doesn't work, you can try other things and get closer to an answer (hopefully) the post when you're hopelessly stuck and we'll help pull you out of the mire
__________________

Got a cough? Go home tonight and eat a whole box of Ex-Lax. Tomorrow, you'll be afraid to cough.
-- Pearl Williams
 
 

Recent GIDBlogWriting a book by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Read a .html file, check that file for links salemite C Programming Language 10 17-Jan-2008 08:56
Re: Conversion: Binary, Decimal, Hexadecimal WaltP C Programming Language 1 10-May-2006 07:49
Including Maps and strings?? maddie C++ Forum 17 05-Jul-2004 07:25
storing a token pointer as a string CoreLEx C Programming Language 1 07-Oct-2003 12:33

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 04:20.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.