You can do this:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main() {
char t[10];
char r[10];
fgets(t, 10, stdin);
int c = 0;
for (int i = 0; i < 10 && t[i] != 0; i++) {
if (isdigit(t[i]) || t[i] == 'i' || t[i] == 'p' || t[i] == '+' ||
t[i] == '-' || t[i] == '*' || t[i] == '/' || t[i] == '^') {
r[c++] = t[i];
}
}
r[c] = '#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main() {
char t[10];
char r[10];
fgets(t, 10, stdin);
int c = 0;
for (int i = 0; i < 10 && t[i] != 0; i++) {
if (isdigit(t[i]) || t[i] == 'i' || t[i] == 'p' || t[i] == '+' ||
t[i] == '-' || t[i] == '*' || t[i] == '/' || t[i] == '^') {
r[c++] = t[i];
}
}
r[c] = '%pre%';
printf("%s", r);
}
';
printf("%s", r);
}
See running on ideone .
I gave a simplified and modernized. Note that checking for loose characters does not have much to do but compare one by one. Of course I could create a solution with an array of valid characters , but I do not think it will pay off in that case, it gets more short but may not be as good at performance.
To check the digits, I prefer to use a ready function ( isdigit()
). You could also compare for a range ( t[i] >= '0' && t[i] <= '9'
) that should be the exact implementation of isdigit()
.
I have fixed a problem that prevents the correct operation in some situations which is the lack of finalization of the string that should always end with a null. Also, now the loop will even find a null, after all the string can be less than 10 characters, without that check it would pick up garbage in those cases.