Reputation: 869
I'm new to C and have this code:
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main(int argc, string argv[])
{
string s = get_string("Enter string: ");
int measure = 0;
for(int i = 0; i < strlen(s);i++)
{
if(isalpha(s[i])==0)
{
measure++;
}
}
printf("Measure is now %i\n", measure);
}
If I place my printf inside of the loop I can see measure incrimenting correctly, but it returns to zero when I have my printf after the loop is complete. I believe this is a scope problem, but my understanding is that a variable, in this case measure, declared outside of the loop has a scope of the main function and so can be modified in for and while loops. I'm thinking this is wrong and I am not sure how to get a value in the scope of a loop passed back to the main function.
Edit: I'm leaving this post as it was originally so the comments below make sense. @MaroBonelli led me to notice that I got confused between two windows and a printf inside of the loop in this code did not actually print the values.
Upvotes: 0
Views: 215
Reputation: 69286
Translating my comment into an answer:
The value will NOT reset to 0 if you don't explicitly reset it somehow. If you meant to count alphabetic characters then this check is wrong:
if (isalpha(s[i]) == 0)
It should be the exact opposite:
if (isalpha(s[i]))
// or
if (isalpha(s[i]) != 0)
From the manual page for isalpha
:
RETURN VALUE
The values returned are nonzero if the character c falls into the tested class, and zero if not.
Upvotes: 1