473,320 Members | 1,957 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Help needed for a string sorting pragram

nk
Hi,
I'm a newbie. The code below sorts names entered.
----------------------------------------------------------------------------
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define SIZE 50

int main()
{
char *a[50];
char hold[50];
char check[50];
char *checkPtr;

int i, j, numb = 0, counter = 0;
for ( i = 0; i < SIZE; i++ ) {
a[i] = (char *) malloc(sizeof(char));
}

while ( numb == 0 ) {
printf("\nHow many names would you like to enter?\n");
gets(check);
numb = strtod(check,&checkPtr);
}

printf("\nEnter the names.\n");

for ( i = 0; i < numb; i++ ) {
gets(a[i]);
counter++;
}

for ( i = 0; i < counter - 1; i++ ) {
for (j = 0; j < counter - 1; j++ ) {

if ( strcmp(a[j],a[j+1]) 0 ) {
sscanf(a[j],"%50s",hold);
sscanf(a[j+1],"%s",a[j]);
sscanf(hold,"%s",a[j+1]);
}

}
}

printf("\n\nThe sorted names are:");

for ( i = 0; i < counter; i++ ) {
printf("\n%s", a[i]);
}

getch();
return 0;
}

---------------------------------------------------------------------------

But if you input names with a whitespace, sscanf functions in the 'for'
loop where the sorting occurs truncates the names from where the
whitespace is encountered:
----------------------------------------------------
if ( strcmp(a[j],a[j+1]) 0 ) {
sscanf(a[j],"%50s",hold);
sscanf(a[j+1],"%s",a[j]);
sscanf(hold,"%s",a[j+1]);
}
----------------------------------------------------
Could you give me any suggestions to prevent this?

Thanks

Aug 12 '06 #1
10 1570
you may use qsort to sort 2D char array
eg:
char szTable[MAX_COUNT][MAX_WORD];

int MyStrCmp( const void *arg1, const void *arg2 )
{
return strcmp( (char*)arg1, (char*)arg2) );
}
qsort(szTable, MAX_COUNT, MAX_WORD, MyStrCmp);

nk 写道:
Hi,
I'm a newbie. The code below sorts names entered.
----------------------------------------------------------------------------
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define SIZE 50

int main()
{
char *a[50];
char hold[50];
char check[50];
char *checkPtr;

int i, j, numb = 0, counter = 0;
for ( i = 0; i < SIZE; i++ ) {
a[i] = (char *) malloc(sizeof(char));
}

while ( numb == 0 ) {
printf("\nHow many names would you like to enter?\n");
gets(check);
numb = strtod(check,&checkPtr);
}

printf("\nEnter the names.\n");

for ( i = 0; i < numb; i++ ) {
gets(a[i]);
counter++;
}

for ( i = 0; i < counter - 1; i++ ) {
for (j = 0; j < counter - 1; j++ ) {

if ( strcmp(a[j],a[j+1]) 0 ) {
sscanf(a[j],"%50s",hold);
sscanf(a[j+1],"%s",a[j]);
sscanf(hold,"%s",a[j+1]);
}

}
}

printf("\n\nThe sorted names are:");

for ( i = 0; i < counter; i++ ) {
printf("\n%s", a[i]);
}

getch();
return 0;
}

---------------------------------------------------------------------------

But if you input names with a whitespace, sscanf functions in the 'for'
loop where the sorting occurs truncates the names from where the
whitespace is encountered:
----------------------------------------------------
if ( strcmp(a[j],a[j+1]) 0 ) {
sscanf(a[j],"%50s",hold);
sscanf(a[j+1],"%s",a[j]);
sscanf(hold,"%s",a[j+1]);
}
----------------------------------------------------
Could you give me any suggestions to prevent this?

Thanks
Aug 12 '06 #2
On 2006-08-12, nk <wh***************@hotmail.comwrote:
Hi,
I'm a newbie. The code below sorts names entered.
----------------------------------------------------------------------------
#include <stdio.h>
#include <conio.h>
Non-standard header. You should remove it and all its dependencies when
posting to clc.
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define SIZE 50

int main()
{
char *a[50];
char hold[50];
char check[50];
char *checkPtr;

int i, j, numb = 0, counter = 0;
for ( i = 0; i < SIZE; i++ ) {
a[i] = (char *) malloc(sizeof(char));
Never case the result of malloc. sizeof (char) is by definition 1. So, you
should have
a[i] = malloc (1);

I do wonder why you wouldn't just use an array of chars; how do you benefit
from pointers?
}

while ( numb == 0 ) {
printf("\nHow many names would you like to enter?\n");
gets(check);
Never, ever, /ever/ use gets(). Use fgets() instead:
fgets (check, sizeof check, stdin);
numb = strtod(check,&checkPtr);
strtod() returns a double. Did you want strtol()?
}

printf("\nEnter the names.\n");

for ( i = 0; i < numb; i++ ) {
gets(a[i]);
You understand that you have Undefined Behavior if the user enters more
than one character here, right? You seriously need to consider your
design. (And if for some reason that is what you want, use fgets().)
counter++;
}
If you add a `--counter;' here, you can avoid those ugly `- 1's. (Or,
you could eliminate the counter++ above and just counter = i, which
will give you the same value.
for ( i = 0; i < counter - 1; i++ ) {
for (j = 0; j < counter - 1; j++ ) {

if ( strcmp(a[j],a[j+1]) 0 ) {
sscanf(a[j],"%50s",hold);
a[j] can only hold 1 char; and consequently one string: "". I'm not sure
why you think that you can get 50 characters into there.
sscanf(a[j+1],"%s",a[j]);
sscanf(hold,"%s",a[j+1]);
Ditto here; the most you can copy is "", because that's all that a[j] and
a[j+1] can hold.
}

}
}

printf("\n\nThe sorted names are:");

for ( i = 0; i < counter; i++ ) {
printf("\n%s", a[i]);
}

getch();
Delete this line, and delete the #include <conio.habove. Nobody want to
have to hit a key to end a program.
return 0;
}
[explanation of what code theorietically should do snipped]

You have a lot to fix, my friend, and there is statistically a 100% chance
that others will find even more that I missed.

--
Andrew Poelstra <http://www.wpsoftware.net/projects>
To reach me by email, use `apoelstra' at the above domain.
"Do BOTH ends of the cable need to be plugged in?" -Anon.
Aug 12 '06 #3
nk

hankssong, i've tried to implement your suggestions on my own but it
failed:
------------------------------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int MyStrCmp( const void *arg1, const void *arg2 );

int main()
{
char *a[2][2] = { { "element4", "element2" }, { "element1",
"element3" } };
int i,j;

qsort(a, 4, 8, MyStrCmp);

for ( i = 0; i < 5; i++ ) {
for ( j = 0; j < 5; j++ ) {
printf("%s\n", a[i][j]);
}
}

return 0;
}

int MyStrCmp( const void *arg1, const void *arg2 )
{
return strcmp( (char*) arg1, (char*) arg2 );
}
------------------------------------------------------------------------------------------------------------
Could you please tell me my mistake?
Thanks very much!!

Aug 12 '06 #4
nk

Andrew, i know that conio.h is a non-standart header but i don't know
any other way to see the output of my program except using getch().

Also, i didn't just use an array of chars because i would have to make
a seperate array for each input, or are there other ways to do an array
of strings that i don't know? I thought that it would be very easy to
swap strings by the use of pointer array.

Is there any way to solve that truncation problem like your fgets()
recommendation?

Thanks a lot for your help.

Aug 12 '06 #5
"nk" writes:
hankssong, i've tried to implement your suggestions on my own but it
failed:
------------------------------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int MyStrCmp( const void *arg1, const void *arg2 );

int main()
{
char *a[2][2] = { { "element4", "element2" }, { "element1",
"element3" } };
int i,j;

qsort(a, 4, 8, MyStrCmp);

for ( i = 0; i < 5; i++ ) {
for ( j = 0; j < 5; j++ ) {
printf("%s\n", a[i][j]);
}
}

return 0;
}

int MyStrCmp( const void *arg1, const void *arg2 )
{
return strcmp( (char*) arg1, (char*) arg2 );
}
------------------------------------------------------------------------------------------------------------
Could you please tell me my mistake?
First of all, you should decide what it is you want to do. Your initial post
looked like someone trying to write a bubble sort and learn something in the
process. hankssong suggested a wildly different approach, use qsort, a
"canned" sorting program.

Do you just want to sort and be done with it? Or are you a student? In the
latter case, try using strcpy in <string.hinstead of sscanf.

You can replace getch with getchar for what you are trying to do. getchar
is part of the standard
Aug 12 '06 #6
Op 12 Aug 2006 11:23:51 -0700 schreef nk:
Andrew, i know that conio.h is a non-standart header but i don't know
any other way to see the output of my program except using getch().
<OTIf you are using the IDE of TC (16 bit DOS), you can use ALT-F5 to see
the output.
Or better use the command line for running your program.</OT>
--
Coos
Aug 12 '06 #7
hankssong wrote:
you may use qsort to sort 2D char array
See below.

Brian
--
Please don't top-post. Your replies belong following or interspersed
with properly trimmed quotes. See the majority of other posts in the
newsgroup, or:
<http://www.caliburn.nl/topposting.html>
Aug 12 '06 #8
Coos Haak wrote:
Op 12 Aug 2006 11:23:51 -0700 schreef nk:
>Andrew, i know that conio.h is a non-standart header but i don't know
any other way to see the output of my program except using getch().

<OTIf you are using the IDE of TC (16 bit DOS), you can use ALT-F5 to see
the output.
Or better use the command line for running your program.</OT>
<Back On Topic>
You can always use the standard getchar function if you can't make your
IDE do the right thing and don't want to use the command line.
--
Flash Gordon
Still sigless on this computer.
Aug 12 '06 #9
On 2006-08-12, nk <wh***************@hotmail.comwrote:
>
Andrew, i know that conio.h is a non-standart header but i don't know
any other way to see the output of my program except using getch().
Try
fflush (stdout);

If you still don't see anything, you should check where stdout points to;
it should go to a console if you want to see it. If you are using an IDE
that opens a window and then closes it, you should learn to use said IDE.
(I've heard that setting a breakpoint at the end of main() will halt the
program and show you the output..)
Also, i didn't just use an array of chars because i would have to make
a seperate array for each input, or are there other ways to do an array
of strings that i don't know? I thought that it would be very easy to
swap strings by the use of pointer array.
How about using
char myarrayofstrings[NUM_STRINGS][MAX_LENGTH];
(The FAQ has the correct ordering; I may have gotten that wrong.)

Otherwise, instead of using malloc(1) how about you malloc (50) or some
other appropriate maximum. (And /enforce/ that maximum by using fgets()
and scanf() correctly.)
Is there any way to solve that truncation problem like your fgets()
recommendation?
How about my fgets() recommendation? :-) I'm not sure what you mean.

--
Andrew Poelstra <http://www.wpsoftware.net/projects>
To reach me by email, use `apoelstra' at the above domain.
"Do BOTH ends of the cable need to be plugged in?" -Anon.
Aug 12 '06 #10
nk

osmium wrote:
First of all, you should decide what it is you want to do. Your initial post
looked like someone trying to write a bubble sort and learn something in the
process. hankssong suggested a wildly different approach, use qsort, a
"canned" sorting program.

Do you just want to sort and be done with it? Or are you a student?
i'm definitely a learner (self-learning) and also i'm a student. so i'm
hungry for any help or knowledge.

So.. Thanks all for your great help. Really!! :)

Aug 12 '06 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: dont bother | last post by:
This is really driving me crazy. I have a dictionary feature_vectors{}. I try to sort its keys using #apply sorting on feature_vectors sorted_feature_vector=feature_vectors.keys()...
6
by: Al Newton | last post by:
I want to use STL's sort algorithm to sort a string vector. Some of the strings are fairly long (300 to 400 chars) and the vector isn't small (5,000 to 10,000 elements). Naturally, sorting time...
5
by: Dr. Ann Huxtable | last post by:
Hello All, I am reading a CSV (comma seperated value) file into a 2D array. I want to be able to sort multiple columns (ala Excel), so I know for starters, I cant be using the array, I need...
4
by: jarkkotv | last post by:
Hi everyone! I'm having a little problem when sorting the ArrayList and I was wondering if there is a .NET guru who can help me out :) I'm trying to sort ArrayList alphabetically in ASP.Net...
1
by: Rahul | last post by:
Hi Everybody I have some problem in my script. please help me. This is script file. I have one *.inq file. I want run this script in XML files. But this script errors shows . If u want i am...
4
by: naknak4 | last post by:
Introduction This assignment requires you to develop solutions to the given problem using several different approaches (which actually involves using three different STL containers). You will...
2
by: rookiejavadude | last post by:
I'm have most of my java script done but can not figure out how to add a few buttons. I need to add a delete and add buttong to my existing java program. Not sure were to add it on how. Can anyone...
1
by: Ahmed Yasser | last post by:
Hi all, i have a problem with the datagridview sorting, the problem is a bit complicated so i hope i can describe in the following steps: 1. i have a datagridview with two columns...
5
by: jrod11 | last post by:
hi, I found a jquery html table sorting code i have implemented. I am trying to figure out how to edit how many colums there are, but every time i remove code that I think controls how many colums...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, youll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: Shllpp 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.