Videos
Working on PSET2 - Readability wherein I have a function set up to count letters. I had this working previously by way of some backwards logic (I had it checking if each char was NOT a space or special char and only counting if true) and decided to redesign it to be more straight-forward. I'm now trying to use isalpha() to check each char, but I'm getting a return of 0 letter(s) every time.
int count_letts(string s)
{
int x = 0;
for(int i = 0, n = strlen(s); i < n; i++)
{
if(isalpha(s[i]) == true)
{
x++;
}
}
return x;
}I have a function for counting words that's almost identical to this using isblank() that works perfectly fine. I've read the man pages and notes from the lectures a couple times, Googled and searched this subreddit, but I don't see anyone with the same issue. What am I doing wrong?
Because the input string retains the \n character causing the input to fail:
Consider using userinput = raw_input("Please enter a word: ").strip() instead...
Also, isalpha() already checks if the length is one or more, reducing your code to:
if userinput.isalpha():
# whatever
And then your syntax error goes away quite nicely... (the extra ) after userinput)
The traceback you've pasted shows different code from your original snippet. You have an extra close bracket after len(userinput), which is the cause of the error.