0

I am new to this and I'm doing the readability program. I'm using isalpha to count the letters and my program compiles but no matter what it says 0 and I can't figure out why.

#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>


int main(void)

{
    string t; int letters = 0;

// Prompts User for text
    {
    t = get_string("Text: ");
    }

//counts letters


for (int i = 0;(t[i]) == '\0'; i++)
    {
         
        if (isalpha(t[i]))
        (letters++);

    }

// prints letters

{ printf("Letters: %i", letters);}
    

1 Answer 1

0

Simple. Look at the for loop:

 for (int i = 0;(t[i]) == '\0'; i++)

The for loop never executes. The test in the second clause is looking for the end of string marker. If it doesn't find it, the test fails and the loop doesn't start the next pass. Since the first char is not the EOS marker, the loop never starts.

Maybe you wanted to use != instead of ==?

Programming tip: While vs for loops.

For loops are intended to be used when there is a known number of passes to be done, whether known at compile time or at run time during execution. WHILE loops are more suited for running until a certain condition is met.

In this case, the code intends to terminate the for loop when a certain condition is met, ie, the EOS marker is found. It is better practice to use a while loop for that. On the other hand, if you had the length of the text, say from a call to strlen(text), then you would have a fixed number of passes to run and a for loop would be the better solution.

What you did is technically correct, but not a "best practice". Just trying to break any bad habits before they start. ;-)

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .