Reputation: 526
i have a string array
what i want to do is that check if string only contains numbers if not giving that error: You entered string
void checkTriangle(char *side1[],char *side2[],char *side3[])
{
int i;
for(i=0;i<20;i++)
if(isdigit(side1[i]) == 0)
{
printf("You entered string");
break;
}
}
prints nothing why?
Upvotes: 2
Views: 10148
Reputation: 2420
#include <string.h>
#include <stdio.h>
void checkTriangle(char *side1)
{
int i;
int found_letter = 0;
int len = strlen(side1);
for( i = 0; i < len; i++)
{
if(side1[i] < '0' || side1[i] > '9')
{
found_letter = 1; // this variable works as a boolean
break;
}
}
if(found_letter) // value 0 means false, any other value means true
printf("You entered a string");
else
printf("You entered only numbers");
}
The parameter "char *side1" could also be passed as "char side1[]"
Upvotes: 1
Reputation: 535
I don't think that you grasp the concepts of arrays and pointers just yet
Your declaration of char *side1[]
is the same thing as saying char **side1
which is really a pointer to a pointer which I'm guessing is not what you want
I think before you start creating functions with pass by reference parameters, you should work with pass by value first. It's better for learning the fundamentals of both the language and programming in general
Upvotes: 2
Reputation: 23699
Your parameter is an array of pointers, not a string. The type of side1
should be char*
, not char*[]
.
void checkTriangle(char *side1, /* ... */)
{
/* ... */
}
To handle floating points values, you can check the format of the string.
#include <ctype.h>
#include <stddef.h>
int checkTriangle(const char *s, size_t n)
{
size_t i;
int p1 = 1;
for (i = 0; i < n; ++i) {
if (s[i] == '.')
p1 = 0;
else if (!isdigit(s[i]) && !p1)
return 0;
}
return 1;
}
BTW, your function is not very well designed. You should rather print in the caller and be independant from the string's size.
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int checkTriangle(const char *s, size_t n)
{
size_t i;
for (i = 0; i < n; ++i)
if (!isdigit(s[i]))
return 0;
return 1;
}
int main(void)
{
char s[32];
size_t n;
fgets(s, sizeof s, stdin);
n = strlen(s) - 1;
s[n] = '\0';
if (!checkTriangle(s, n))
puts("You entered string");
return 0;
}
If you are allowed to use the standard C library entirely, can also use strtod
.
Upvotes: 1