I have so far, in my C code where it counts everything in a user given string, however, I only want it to count letters.
Whenever I try and take out or change the spaces counter my code ends up breaking and forces me to manually stop it.
I would like to use the spaces sometime later as a method to count words but I'd rather try and get the letters done first.
What I mean by it breaks is that the code will proceed to infinitely do nothing. I found this out when instead of putting something down I had it printed and it constantly repeated what was given with no stopping.
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
string s = get_string("Text: ");
int n = 0;
while (s[n] != '\0')
{
if (isalpha(s[n])) //counts letters
{
n++;
}
else
{
}
}
I would like to try and keep the code similar, but if its easier, a different way.
Also I would like to keep it to where it will be able to process a string given by the user.
If you look closely at the cycle:
while (s[n] != '\0')
{
if (isalpha(s[n])) //counts letters
{
n++;
}
}
you will notice that when s[n]
is not alpha, n
is not incremented, so you're stuck in an infinite loop.
The counter and the iterator should be different variables:
int count = 0;
//...
while (s[n] != '\0')
{
if (isalpha(s[n]))
{
count++; //counts letters
}
n++; //increment iterator
}
You have an infinite loop as soon as a non letter character is encountered due to the else statement
int n = 0;
while (s[n] != '\0')
{
if (isalpha(s[n])) //counts letters
{
n++;
}
else
{
}
}
You have to use two variables. The first one is to store the number of letters and the second one is to traverse a character array.
In such a case it is better to use the for loop instead of the while loop.
For example
size_t n = 0;
for ( size_t i = 0; s[i] != '\0'; i++ )
{
if ( isalpha( ( unsigned char )s[i] ) ) //counts letters
{
n++;
}
}
Pay attention to that there is no sense to declare the variable n
as having the signed integer type int
. It is better to declare it as having the unsigned integer type size_t
. It is the type that for example the string function strlen
has.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.