There are multiple problems in your code:
gets()
must no longer be used in C programs, it has been removed from the C Standard as of C11 because it cannot be used safely. You should use fgets()
instead and handle the trailing newline explicitly.
to remove the redundant spaces when copying the string, you need a separate index into the destination string and the source string.
you also need to set a null terminator at the end of the destination string.
avoid naming a variable l
because it looks confusingly close to 1
.
you should output the modified string in main()
and let even()
perform the cleaning without this side-effect.
your indentation style is very unusual. Using a more classic style will make the code more readable for the majority of programmers (including yourself).
Here is a modified version:
#include <stdio.h>
#include <string.h>
void even(const char *p, int len, char *q);
int main() {
char str2[80];
char str1[80];
printf("Enter a sentence\n");
if (!fgets(str1, sizeof str1, stdin)) {
// handle unexpected end of file gracefully
return 1;
}
int len = strlen(str1);
// strip the trailing newline if any
if (len > 1 && str1[len - 1] == '\n') {
// updated len is still the length of the string
str1[--len] = '\0';
}
even(str1, len, str2);
printf("%s\n", q);
return 0;
}
void even(const char *p, int len, char *q) {
int x, y;
for (x = y = 0; y < len;) {
*(q + x) = *(p + y);
x++;
y++;
if (*(p + y - 1) == ' ') {
// skip redundant blanks
while (*(p + y) == ' ') {
y++;
}
}
}
// set the null terminator
*(q + x) = '\0';
}
Note also that the array syntax is much more readable than explicit pointer arithmetic and dereferencing as above. Here is a simplified version of even()
:
void even(const char *p, int len, char *q) {
int x, y;
for (x = y = 0; y < len;) {
q[x] = p[y];
x++;
y++;
if (p[y - 1] == ' ') {
// skip redundant blanks
while (p[y] == ' ') {
y++;
}
}
}
// set the null terminator
q[x] = '\0';
}