c strcat with pointer

Favolas picture Favolas · Apr 2, 2012 · Viewed 12.9k times · Source

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 inputs te12abc the output should be 12.

This is my first try:

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

#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

cnicutar picture cnicutar · Apr 2, 2012

You're making it harder than it has to be. You don't need strcat:

/* Untested. */   
char *pont = palavra;
char *pont2 = palavra2;

while (*pont) {
    if (isdigit(*pont))
        *pont2++ = *pont;

    pont++;
}
*pont2 = 0;