I decided to use a different approach: get a string of letters (with fgets) separated by commas then delete the commas that were input to get a clean letter array. However, my logic is not correct. I debugged with gdb:
Code:
Please enter 4 letters separated by commas: a,b,c,d
Breakpoint 1, main () at prosqueeze.c:80
80 if(cond == 1 && len == n)
(gdb) print cond
$1 = 0
(gdb) print len
$2 = 8
Code:
#include <stdio.h>
#include <stdlib.h> /* for malloc() and free() */
#include <ctype.h>
#include <string.h>
#ifndef MAXLINE
#define MAXLINE 100
#endif
#ifndef ALPHA
#define ALPHA 26
#endif
#ifndef STRNUM_MAX
#define STRNUM_MAX 10
#endif
void squeeze(char*, char*);
void noCommas(char*);
int isStrAlpha(char*);
/* the function removes t characters chosen by the user from the s string */
void squeeze(char* s, char* t)
{
}
/* noCommas: delete all commas from s */
void noCommas(char* s)
{
int i, j;
for(i = 0, j = 0; s[i] != '\0'; i++)
if(s[i] != ',')
s[j++] = s[i];
}
/* isStrAlpha: verify if the entire string is alphabetic */
int isStrAlpha(char* s)
{
int i;
for(i = 0; s[i] != '\0'; i++)
if(!isalpha(s[i]))
return 0;
return 1;
}
int main(void)
{
char* s;
char* t;
char* strnum;
int n;
int i = 0;
int len = 0;
int cond = 0;
s = malloc(MAXLINE * sizeof(char));
t = malloc(ALPHA * sizeof(char));
strnum = malloc(STRNUM_MAX * sizeof(char));
printf("Enter the word you want: ");
fgets(s, MAXLINE, stdin);
printf("You entered: %s", s);
do {
printf("Enter the number of letters of the alphabet you want (1-26): ");
if(fgets(strnum, STRNUM_MAX, stdin))
n = atoi(strnum);
} while(n < 1 || n > 26);
printf("You entered %s", strnum);
printf("Please enter %d letters separated by commas: ", n);
if(fgets(t,ALPHA,stdin))
{
noCommas(t);
cond = isStrAlpha(t);
len = strlen(t);
if(cond == 1 && len == n)
{
squeeze(s, t);
}
else
{
printf("You entered an invalid character.\n");
exit(0);
}
}
for(i = 0; i < n; i++)
{
printf("%c ", t[i]);
}
free(s);
free(t);
free(strnum);
return 0;
}