Question

I am using isalpha() to determine if there are characters on the line and it is showing that the line "90 1 0" contains alphabetic characters.

Here is the relevant code

bool digitTest(char *test, int arysize)
{
int i;
for (i =0; i<arysize; i++)
{
    if ((isalpha(test[i])) != 0){

        return 0;
    }

    if (i==arysize)
        return 1;
            i++;
}
return 1;
}

It is called here

char buffer[4096] = {};

while(NULL!=fgets(buffer, sizeof(buffer), fp)){
    if (digitTest(buffer, 4096) == 0){

        printf ("contains alpha\n");
        continue;
    /*printing code if there is no alphabetic characters below, i do not believe it is  relevant*/

and this is output

1
1
1
contains alpha 
contains alpha
contains alpha 
25123.90
54321.23
6

and input

1
1
1
89 23.5 not a number
90 1 0
-5.25 not a number 10000
25123.90 54321.23 6
Was it helpful?

Solution 2

It Looks like you might be accessing locations in memory that contain characters, Change your code to

char buffer[4096] = {};
memset(buffer, 0, 4096);

while(NULL!=fgets(buffer, sizeof(buffer), fp)){
if (digitTest(buffer, strlen(buffer)) == 0){ //get actual length of buffer

    printf ("contains alpha\n");
    continue;

EDIT

In order to make your code not respond to either \n or \r do

bool digitTest(char *test, int arysize)
{
int i;
for (i =0; i<arysize; i++)
{
    if( test[i] == '\r' || test[i] == '\n')
        return 1;
    if ((isalpha(test[i])) != 0){

        return 0;
    }

    if (i==arysize)
        return 1;

}
return 1;
}

OTHER TIPS

The code has a few problems:

  • You shouldn't check all buffer. Check buffer until \0. because the output of fgets is a C-style string.

  • Second problem is an extra i++ in function digitTest. You should remove it.

  • You don't need arysize any more.

Use this digitTest function instead

int digitTest(char *test)
{
  int i;
  for (i=0; test[i] && test[i] != '\n'; i++)
  {
     if (isalpha(test[i]) != 0)
        return 0;
  }
  return 1;
}

(maybe has minor bugs, I didn't test it)

And call it like this:

while( fgets(buffer, sizeof(buffer), fp) ) {
    if (!digitTest(buffer)) {
        printf ("contains alpha\n");
        continue;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top