I'm trying to use pointers and strcat from C. This is part of my learning process.
The idea is the user inputs a string that contains digits and the output should return only the digits.
So, if the user inputste12abc the output should be 12.
This is my first try:
#include
#include
#include
#include
#define SIZE 10
int main()
{
char palavra[SIZE];
char palavra2[SIZE];
char *pont = palavra;
char *pont2 = palavra2;
printf("Insert the string\n");
scanf("%s", palavra);
do{
if (isdigit(*pont)){
strcat(palavra2, *pont);
}
*pont++;
}while (*pont != '\0');
printf("\nThe number is:\n%s\n", palavra2);
return 0;
}
I believe that the pointer is working as expected but can't understand why strcat is not working.
Made a second try that is the program finds a number, stores that char in one variable and only then try to use strcat with that variable. Here is the code:
int main()
{
char palavra[SIZE];
char palavra2[SIZE];
char temp;
char *pont = palavra;
char * pont2 = &temp;
printf("Insert the string\n");
scanf("%s", palavra);
do{
if (isdigit(*pont)){
temp = *pont;
strcat(palavra2, pont2);
}
*pont++;
}while (*pont != '\0');
printf("\nThe number is:\n%s\n", palavra2);
return 0;
}
Once again it gives me problems at strcat.
Made one last attempt but without pointer and still strcat does not work. Here is the code:
int main()
{
int i = 0;
char palavra[SIZE];
char palavra2[SIZE];
char temp;
printf("Insert the string\n");
scanf("%s", palavra);
do{
if (isdigit(palavra[i])){
temp = palavra[i];
strcat(palavra2, palavra[i]);
}
i++;
}while (palavra[i] != '\0');
printf("\nThe number is:\n%s\n", palavra2);
return 0;
}
Can you point me to the right direction? Don't now what more can I do..
Regards,
favolas
Answer
Remove * (dereference),
strcat(palavra2, pont);
strcat expects a char* not a char
but this version appends the whole rest.
you have to create a nul-terminated string.
And the * is useless
*pont++;
This does the job
pont++;
now all at once
int main()
{
char palavra[SIZE];
char palavra2[SIZE];
char c2[2] = "a";
char *pont = palavra;
char *pont2 = palavra2;
printf("Insert the string\n");
scanf("%s", palavra);
do{
if (isdigit(*pont)){
c2[0] = *pont;
strcat(palavra2, c2);
}
pont++;
}while (*pont != '\0');
printf("\nThe number is:\n%s\n", palavra2);
return 0;
However, this is too complicated
int main()
{
char palavra[SIZE];
char palavra2[SIZE];
printf("Insert the string\n");
scanf("%s", palavra);
char *pont = palavra;
char *pont2 = palavra2;
while (true) {
char c = *pont ++;
if (c == 0) break;
if (isdigit(c)){
*pont2++ = c;
}
};
printf("\nThe number is:\n%s\n", palavra2);
return 0;
No comments:
Post a Comment