I'm working on the readability task in pset2.
I've made a new function which is going to count
each letter in a string.
What I want to do, is to get a user's input string, save it in a variable text
and
pass it to the function count_letters()
.
Inside the function, I filter out everything that is not chars of a-z and A-Z.
If I just spit out each char directly, inside the loop, it prints correct, and consolidates every word without spaces and special characters.
Inside the function, I'm also copying each char to a new array (the same letters I printed out the line above)
When I try to print out the new array, it only prints out the first word(where there is a space, or a special character).
Now, I don't understand what's happening here. Why isn't everything in the if-statement being properly copied into my new array? Why are spaces and special characters ignored inside the loop, but not ignored when they're copied from WITHIN the loop?
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int count_letters(char *text);
int main(void)
{
string text = get_string("Text: ");
count_letters(text);
}
int count_letters(char *text)
{
int l = strlen(text);
char *letter_box = (char*)malloc(strlen(text+1));
for(int i = 0; i < l; i++){
if((text[i] >= 'a' && text[i] <= 'z') || (text[i] >= 'A' && text[i] <= 'z'))
{
letter_box[i] = text[i];
printf("%c", text[i]); // PRINTS CORRECTLY
}
}
printf("\n");
printf("%s", letter_box); // ONLY PRINTS FIRST WORD
return 0;
}