I am trying to write a program that counts several elements in a string. The first one of those being letters.
The assignment is part of the CS50 week 2 problem set, hence the libraries included.
Using the while
condition I was able to count every single character, but the code stopped working once I´ve added isalnum
(which checks if the character is alphanumerical).
What am I doing wrong?
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(void) {
string text = get_string("Text: ");
printf("%s, \n", text);
int letters = 0;
while (text[letters] != '\0') {
if (isalnum(text[letters])) {
letters++;
}
}
printf("%i \n", letters);
}
Here is shown how a correct loop can be defined
size_t letters = 0;
for ( size_t i = 0; text[i] !='\0'; i++ )
{
if ( isalnum( ( unsigned char )text[i] ) )
{
letters++;
}
}
printf( "%zu\n", letters );
If you want to use a while loop then it can look for example like
size_t letters = 0;
size_t i = 0;
while ( text[i] !='\0' )
{
if ( isalnum( ( unsigned char )text[i++] ) )
{
letters++;
}
}
printf( "%zu\n", letters );
Pay attention to that the function isalnum
detects letters and digits. If you need to count only letters then use the function isalpha
.