0

我很难根据自己的需要调整功能。首先查看这三个文件并注意我必须如何在 main 函数中调用 f_texture 函数才能使其工作:

外部人员.h

#ifndef EXTERNS_H_
#define EXTERNS_H_

extern char t_about[100];
extern int friction;

extern int f_texture(char* ,char*);

#endif

函数A.c

#include <stdio.h>
#include "externs.h"

int main()
{
    f_texture("rough","friction");
    printf("Friction: %d\n", friction);
    f_texture("rough","t_about");
    return 0;
}

函数B.c

#include "externs.h"
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
char t_about[100];
int friction;

int f_texture(char* texture,char* what_is_needed)
{
    /*Checking if both values are present*/
    assert(what_is_needed);
    assert(texture);

    /*Static array in order to prevent it's disappearance*/
    memset(t_about, '\0', sizeof(t_about));

    /*Configuring variables for desired texture*/
    if (strcmp(texture, "smooth") == 0)
    {
        strcpy(t_about, "The surface is perfectly smooth, without any "
            "protuberances.\n");
        friction = 0;
    }
    else if (strcmp(texture, "rough") == 0)
    {
        strcpy(t_about, "Rough bumps can be feeled under my fingertips.\n");
        friction = 4;
    }
    /*In case of absent keyword of desired texture it will crash the program*/
    else
    {
        assert(!what_is_needed);
    }

    /*Returning desired value*/
    if (strcmp(what_is_needed, "t_about") == 0)
    {
        int i=0;
        while (t_about[i] != '\0')
            {
            printf("%c", t_about[i]);
            i++;
            }
    }
    else if (strcmp(what_is_needed, "friction") == 0)
    {
        return friction;
    }
    /*In case of absent keyword of desired value it will crash the program*/
    else
    {
        assert(!what_is_needed);
    }

    return 0;
}

现在这是我的问题:如何重写此代码以使其可以在不使用引号的情况下调用 f_texture 函数?我的意思是输入 f_texture(abcd,efgh) 而不是 f_texture("abcd","efgh")。我注意到在我写完这段代码之后就需要这种方式。提前致谢。

4

4 回答 4

2

如果您不想将字符串常量分配给变量或预处理器对象宏,另一种选择是使用预处理器函数宏,使用字符串化功能:

#define call_f_texture(a,b) f_texture(#a,#b)
....
call_f_texture(rough,friction);

C预处理器将把它变成

f_texture("rough","friction");
于 2013-12-13T09:35:57.943 回答
1

您还可以使用一些宏:

#define ROUGH    "rough"
#define FRICTION "friction"
#define T_ABOUT  "t_about"

int main()
{
    f_texture(ROUGH, FRICTION);
    printf("Friction: %d\n", friction);
    f_texture(ROUGH, T_ABOUT);
    return 0;
}
于 2013-12-13T09:24:01.153 回答
0

你可以这样做,

char rough[]="rough";
char friction[]= "friction";

并打电话

f_texture(rough, friction);
于 2013-12-13T09:19:17.847 回答
0
char a[MAX] = "rouch";
char b[MAX} = "friction";

int main()
{
      f_texture();
      ...
}

int f_texture()
{
    /*Checking if both values are present*/
    assert(b);
    assert(a);
}

或者

int f_texture(char* a,char* b)
{
    /*Checking if both values are present*/
    assert(b);
    assert(a);
    ...
}

int main()
{
    char a[MAX] = "rouch";
    char b[MAX} = "friction";
    f_texture(a,b);
    ...
}
于 2013-12-13T09:19:39.983 回答