Click to See Complete Forum and Search --> : Checking a String


Arcane_Disciple
09-22-2002, 10:22 AM
I have to write a program that checks a string containg a pile of coins. (p=penny, n-nickel, etc.) Say the user enters "pnqdpd". My function is supposed to check that string and see that the dime is the smallest, then flip the pile so that the pile now has the dime on top. It will then check again until it comes to the penny and so on and so forth until everything is in the proper size order. What is the easiest way to do this?

X_console
09-22-2002, 02:50 PM
How about something like this?


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100

int main()
{
char pile[MAX];
char coins[] = { 'p', 'n', 'd', 'q' };
char current_coin;
char new_pile[];
int index;
int i;
int j;

printf("Enter coins (p, n, d, q): ");
fgets(pile, MAX, stdin);

index = 0;
for (i = 0; i < strlen(pile); i++)
{
current_coin = coins[i];
for (j = 0; j < strlen(pile); j++)
{
switch(current_coin)
{
case 0: /* penny */
new_pile[index] = pile[j];
index++;
break;

case 1: /* nickel */
new_pile[index] = pile[j];
index++;
break;

case 2: /* dime */
new_pile[index] = pile[j];
index++;
break;

case 3: /* quarter */
new_pile[index] = pile[j];
index++;
}
}
}
printf("New pile: %s\n", new_pile);

return 0;
}

Arcane_Disciple
09-22-2002, 04:18 PM
thank you much. that helps more than i can tell you.