Monday, May 24, 2010

C programming question?

I have to write a program that asks the user to write a sentence and then after hitting the return key, the program rewrites the sentence but with only one space between the words if there was more than one. for example:





This is a sentence with many spaces





the program should write:





This is a sentence with many spaces





So the program ignored all the spaces and put only one space between sentences.





Please no use of arrays, the program should be very very simple.... no advanced programming should be included.





Any ideas/hints/tips that might help.





Thank You all!!

C programming question?
Well, first of all, you have no choice to use an array; a character array (pointer to char) to hold the typed in sentence. Once you have the array of chars you can do a simple for loop. Something like...





int j = 0;


for (int i = 0; i %26lt; iSentenceLen; i++)


{


....if ( pSentence[i] != 20 || i == 0 || pSentence[i-1] != 20 )


........pSentence[++j] = pSentence[i];


}


pSentence[j] = "\0";
Reply:Use strtok from the string.h library, why don't you?





Declare an array and a pointer. As in:


char Buffer[80], *Ptr;





Then do a gets(Buffer); and if you are using GCC you will be told by the linker gets is dangerous and should never be used.





Instead of assigning Buffer's address to Ptr, what you do is your first call to strtok:





Ptr = strtok(Buffer, " ");





Then do a while loop. Once strtok runs out of tokens to return it returns a null string. therefore:





while (Ptr!=NULL){





Since you have probably made a successful call to Buffer already, a NULL pointer will tell strtok to scan from exactly where it is in Buffer right now. So:





printf("%26amp;s ", Ptr);


Ptr=strok(NULL," ");


}





Then you're done so bail.


return 0;





Look up strtok. It's very helpful.





headers would be #include %26lt;stdio.h%26gt;


#include %26lt;string.h%26gt;
Reply:Easy.





Once you've got you string into (I'll leave you to do that) you do the following loop, the string is in sSent.





char *sToken = strtok (sSent, " ");





while (sToken)


{


printf ("%s ", sToken);


sToken = strtok (0, " ");


}


No comments:

Post a Comment