سؤال

Some guy presented me with a beautiful code in my other question. Here it is:

#include <iostream>
#include <cstring>

using namespace std;

void encode(char* source, char const* alpha)
{
    int i, j;
    int len = strlen(source);
    for (i = 0; i < len; i++)
    {
        if (source[i] >= 'a' && source[i] <= 'z')
        {
            j = source[i] - 'a';
            source[i] = alpha[j];
        }
    }
}

int main(void)
{
    char source[1001];
    char alpha[27];
    cin.getline(source, 1001);
    cin.getline(alpha, 27);
    encode(source, alpha);
    cout << source;
    return 0;
}

What should I do to transform this void function into a char* one (it should become char* encode(char* source, char const* alpha))? Apparently as it won't be a 'void' it should return a value but what value? Those pointers confuse me immensely.

هل كانت مفيدة؟

المحلول

#include <iostream>
#include <cstring>

using namespace std;

char* encode(char* source, char const* alpha)
{
    int i, j;
    int len = strlen(source);
    for (i = 0; i < len; i++)
    {
        if (source[i] >= 'a' && source[i] <= 'z')
        {
            j = source[i] - 'a';
            source[i] = alpha[j];
        }
    }
    return source;
}
int main()
{
    char source[1001];
    char alpha[27];
    cin.getline(source, 1001);
    cin.getline(alpha, 27);
    cout << encode(source, alpha);
    return 0;
}

Do something like that. And if you want to change a char array of main, your void function would work. :)

نصائح أخرى

char* encode(char* source, char const* alpha)
{
    int i, j;
    int len = strlen(source);
    for (i = 0; i < len; i++)
    {
        if (source[i] >= 'a' && source[i] <= 'z')
        {
            j = source[i] - 'a';
            source[i] = alpha[j];
        }
    }
    return source;
}

Though it doesn't look like your doing anything with that return value.

(Were you supposed to return a copy of the char array, or is modifying in-place it okay?)

Returning char * really only makes sense if you're trying to alert the calling function an error has occurred:

char *encode(char *source, char const *alpha)
{
    int i, j;
    int len = strlen(source);

    /* Check For Argument Errors */
    if((source == NULL) || (alpha == NULL))
        return NULL;

    for (i = 0; i < len; i++)
    {
        if (source[i] >= 'a' && source[i] <= 'z')
        {
            j = source[i] - 'a';
            source[i] = alpha[j];
        }
    }

    return source;
}

The calling function can check for errors like this:

if(encode(source, alpha) == NULL)
{
    printf("Encoding error!\n");
    return -1;
}
else
{
    cout << source;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top