Hi everyone I'm starting to learn C programming and I have a bad time in making a program that sort the words in ascending order using strtok. Like this:
INPUT: I am good.
OUTPUT: am
good
i
Please help me, thanks!
Hi everyone I'm starting to learn C programming and I have a bad time in making a program that sort the words in ascending order using strtok. Like this:
INPUT: I am good.
OUTPUT: am
good
i
Please help me, thanks!
Last edited by programmerc; 12-21-2012 at 09:04 AM. Reason: Typographic error
Post up what you have tried. That fulfills the requirements of the forum, AND it helps us to help you, as well. The doctor must see the patient.
I do not have a code yet..
Hmm.. Then take your time to write some code and then post back if needed
Code - functions and small libraries I use
It’s 2014 and I still use printf() for debugging.
"Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson
Well the first step is using strtok so you can just do
INPUT: I am good.
OUTPUT:
I
am
good
Then we'll talk about sorting, if you can't figure it out in the meantime.
A development process
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
Code:#include<stdio.h> #include<conio>.h> void main(){ int i,j,n; char str[20][20],temp[20]; puts("Enter the no. of string to be sorted"); scanf("%d",&n); for(i=0;i<=n;i++) gets(str[i]); for(i=0;i<=n;i++) for(j=i+1;j<=n;j++){ if(strcmp(str[i],str[j])>0){ strcpy(temp,str[i]); strcpy(str[i],str[j]); strcpy(str[j],temp); } } printf("The sorted string\n"); for(i=0;i<=n;i++) puts(str[i]); getch(); }
I didn't use strtok here, because I do not know how to use it in sorting.
You don't use it in sorting. What you probably do is use it prior to the sorting, to break up the sentence into individual words that can be sorted.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
It is possible that I will store the individual words into a new variable?
I expect that you would have an array to store the individual words, or pointers thereof, then you would sort this array.Originally Posted by programmerc
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Tokenization example with strtok on the forum
Need help reading from txt
You can modify this to fit your problem specification, just sort the words after they are collected.