1

I am trying to write a code to get the number of letters in a text as a variable. I used a for loop to check each character in the text to see whether it is a letter or not. The problem is, I can't get the 'letters' variable out for further use in the continuation of the code since it is in a for loop. Is there a better way to do it?

#include<stdio.h>
#include<cs50.h>
#include<string.h>
int non_letter = 0;
int main(void)

{
    string text = get_string("Text:\n");                //get 'text' from user

    int size = strlen(text);                           //get length of 'text' string

    for (int x = 0; x < size  ; x++)

    {

         if (text[x] < 65 || text[x] > 122)               //get the number of non letter in 'text'
        {
            non_letter = non_letter + 1;
        }

         int letters = x - non_letter + 1;

    }
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
sivhaslee
  • 9
  • 1
  • Declare `letters` outside the loop. In fact, you don't need to set `letters` continuously inside the loop. Just set it once outside the loop. – kaylum May 02 '20 at 01:38
  • Maybe I am doing it wrong but when I tried declaring letters outside the for loop, it didn't work since the variable x is still inside the for loop. I need x to declare letters correctly. – sivhaslee May 02 '20 at 01:49
  • You don't need `x`. Use `size`: `int letters = size - non_letter;`. – kaylum May 02 '20 at 01:50
  • Thank you so much. It works now. – sivhaslee May 02 '20 at 01:54
  • And if you really wanted/needed to use `x` next time then just declare that before the loop too instead of as part of the loop. `int x; for (x=0, ...)` – kaylum May 02 '20 at 01:57
  • Ah, thank you. I tried declaring x before using it in the for loop but I did `int x = 0; for (x, ...)` instead and it didn't compile since the x in loop was unused. Again, thank you for your help. – sivhaslee May 02 '20 at 02:09

0 Answers0