1

I'm working with C and I need to check that the user inputed second command line argument argv[1] is made up of only alphabetical charchaters and if not, to do what is inside the else loop. I used the is alpha function but when i compile and run the program no matter what my second command line argument is (alphabetical or otherwise), its always executing the "else loop". How do i fix this?

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

int main(int argc, string argv[])
{
  int a  = argc;    

  if (a != 2)
  {
    return 1;    
  }

  string b = argv [1]; 
  int c = strlen(b);
  string m;

  for (int i = 0; i < c; i++)
  {
    if (isalpha(b[c]))
    { 
      m = GetString();    
    }
    else
    {
      printf("Please provide a valid keyword\n");
      return 1;
    }         
  }
}  
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
TeachMe
  • 155
  • 2
  • 3
  • 11

2 Answers2

10

Try replacing

if (isalpha(b[c]))

with

if (isalpha(b[i]))

Currently you are checking the element at the index which is the result of strlen(b) at every iteration of your loop. Because array indices are zero based in C b[strlen(b)] is referencing '\0', the null terminator.

In reference to the Keith Thompson comment below and the answer to this question you should actually be casting the value passed to isalpha to an unsigned char to ensure that undefined behaviour is not invoked.

Thus you should change your code to

if (isalpha((unsigned char)b[i]))

to ensure there is no UB

Community
  • 1
  • 1
mathematician1975
  • 21,161
  • 6
  • 59
  • 101
  • 8
    `isalpha()` doesn't simply take a `char` argument. It takes an `int` argument whose value is converted from `unsigned char`. If plain `char` is signed (as it commonly is), then `isalpha(c)` has undefined behavior if `c < 0` (and `c != EOF`). Change `isalpha(b[i])` to `isalpha((unsigned char)b[i])`. (This is almost certainly not the cause of the OP's problem.) – Keith Thompson Jul 25 '15 at 23:16
  • Thanks, that helped :) – TeachMe Jul 25 '15 at 23:21
  • No you haven't. It should be `isalpha((unsigned char)b[i])`. – user207421 Jul 25 '15 at 23:38
0

Use isalpha(b[i]) instead of isalpha(b[c]) like this:

if (isalpha(b[i]))
{ 
  m = GetString();    
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
RatikBhat
  • 61
  • 11