My program is supposed to allow the user to enter a sentence in CAPS. Then the program will change the letters to lowercase and print each of the words backwards on separate lines. For example, if the user entered HELLO WORLD, the output would be:
olleh
dlrow
My code has a problem in that for some sentences, two words get printed on one line. For example, if I enter HELLO MY NAME IS JOHN, the output is:
olleh
eman ym
nhoj si
I'd be very grateful to anyone who knows how to fix this problem!
Here's my code:
Code:
/ * This program will use character strings, functions, and pointer notation
* to display each word of a sentence in lower-case, reverse order on
* separate lines.
*/
#include <stdio.h>
#include <ctype.h>
void prtWords (char *pSentence);
int str_len (char *s1);
void main (void)
{
char pSentence[100], choice;
do {
printf ("Enter a sentence: ");
fflush (stdin);
gets (pSentence);
prtWords (pSentence);
/* .. . . */
fflush (stdin); /* Flush buffers to standard input */
printf ("\nWould you like to enter another sentence? ");
choice = getchar ();
printf ("\n");
} while (choice !='n' && choice !='N');
getchar ();
}
void prtWords (char *pSentence)
{
char tmpstrg [80];
char pT;
int length, n, end, j, sum = 0;
length = str_len (pSentence);
for (n=0; n<length; n++)
{
if (isspace (pSentence[n]))
{
end = n;
sum = sum + n;
for ( j = end - 1; j >= 0; j--)
{
tmpstrg[j] = *pSentence;
++pSentence;
}
for (j = 0; j<=end-1; j++)
{
pT = tmpstrg[j];
pT = tolower (pT);
printf ("%c", pT);
}
printf ("\n");
++pSentence;
sum++;
}
}
for ( j = length - sum -1; j >= 0; j--)
{
tmpstrg[j] = *pSentence;
++pSentence;
}
for (j = 0; j<=length-sum-1; j++)
{
pT = tmpstrg[j];
pT = tolower (pT);
printf ("%c", pT);
}
}
int str_len (char *s1)
{
char *cp = s1;
while (*cp)
++cp;
return (cp - s1);
}