0

In the main function if i simply declare the replacement character like this..

c = '*';

the program will keep looping normal and work normal after user enters y or Y to proceed.

But if i want the user to enter the replacement character and do this..

c = getchar();

after the user enters either y or Y, the loop ends and the program just closes. Why is this?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define BUFF_SIZE 512


void getRandomStr(char s1[]);
void strreplace(char s1[], char chrs[], char c);
void check(char s2[], char chrs[]);
char cont(void);

int main()
{
    char s1[BUFF_SIZE];
    char s2[BUFF_SIZE], c;
    char proceed = 0;


    do {

        getRandomStr(s1);
        printf("Your random string is: %s\n", s1);


        /* gets(s1) */
        printf("\nPlease enter up to 20 letters to be replaced: ");
        gets(s2);
        printf("\nPlease enter a replacement character (Ex. *, $, etc.): ");
        c = getchar();


        check(s1, s2);


        printf("\nModified string after replacement is: ");
        strreplace(s1, s2, c);


        proceed = cont();

    } while (proceed == 'Y' || proceed == 'y');

}


void getRandomStr(char s1[]) {

    int i;

    srand(time(NULL));
    for (i = 0; i < 41; i++) {

        char c = rand() % 26 + 'A';
        s1[i] = c;

    }

    s1[41] = '\0';
}

void strreplace(char s1[], char chrs[], char c)
{
    int i = 0;

    while (chrs[i] != '\0') {

        for (int j = 0; s1[j] != '\0'; j++) {

            if (s1[j] == chrs[i])
            {

                s1[j] = c;

            }
        }

        i++;
    }
    puts(s1);
}


char cont()
{

    char proceed;
    printf("\nWould you like to run the program again (y/n)? ");
    scanf_s("%c%*c", &proceed);
    return proceed;
}

void check(char s2[], char chrs[])
{
    int i = 0;

    while (chrs[i] != '\0') {

        for (int j = 0; s2[j] != '\0'; j++) {

            if (!(chrs[i] >= 'A' && chrs[i] <= 'Z'))
            {

                printf("An invalid character was entered.\n");
                break;
            }
        }

        i++;
    }
} 

0 Answers0