Reputation: 191
I am trying to write a function in C that takes a string, for example: "abc123def"
and returns a number in string form: "123"
.
I have little experience with C so I was wondering if I am using the isDigit()
function correctly. My code is below, if there is a better way to solve the problem I would appreciate help. Thanks!
char findNumber(char *str1)
{
char num1[] = "";
int i = 0;
int j = 0;
while(str1[i] != '\0') {
if(isDigit(str1[i])) {
num1[j] = str1[i];
j++;
}
i++;
}
num1[j] = '\0';
return num1;
}
int main(int argc, const char* argv[])
{
char str2[] = "!3254";
printf(findNumber(str2));
return 0;
}
I'm getting errors such as:
undefined reference to `isDigit'
and
return makes integer from pointer without a cast
What could be causing these?
Upvotes: 0
Views: 242
Reputation: 3912
This should work:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char* findNumber(char *str1)
{
char* num1=malloc(strlen(str1)+1);//allocate memory for the number
int i = 0;
int j = 0;
while(str1[i] != '\0') {
if(isdigit(str1[i])) {//isdigit() is in ctype.h
num1[j] = str1[i];
j++;
}
i++;
}
num1[j] = '\0';
return num1;
}
int main(int argc, const char* argv[])
{
char str2[] = "!3254";
char* number=findNumber(str2);
printf("%s\n",number);
free(number);//free the allocated memory
return 0;
}
Upvotes: 2
Reputation: 55609
Your function needs to return char *
since you're not just returning a single character, but a bunch of characters.
After a quick Google search I found that isdigit
is defined in ctype.h
, so lower-case D
and include ctype.h
.
Also, you've got yourself some undefined behaviour there, since you only allocate memory to num1
for a length 0 string. char *num1 = malloc(someSize)
is one option, which should have a corresponding free
somewhere if the program were to execute for anything more than a few seconds / minutes.
Code after fixes:
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_SIZE 100
char *findNumber(char *str1)
{
char *num1 = malloc(MAX_SIZE);
// using "strlen(str1)+1" instead of MAX_SIZE might be preferred
int i = 0, j = 0;
while(str1[i] != '\0') {
if(isdigit(str1[i])) {
num1[j] = str1[i];
j++;
}
i++;
}
num1[j] = '\0';
return num1;
}
int main(int argc, const char* argv[])
{
char str2[] = "!3254";
printf(findNumber(str2));
return 0;
}
Test.
Upvotes: 3