从主函数访问变量

时间:2013-06-29 09:25:29

标签: c++

我想访问loadconfig函数中的值,但总是出错:

  

请求'LoadConfig'中的成员'a',它是非类型'int()'

string trainData, testData, simName;
int b, i;

int LoadConfig()
{
    int a;
    ifstream fin("kddcup.txt"); 

    while(getline(fin,trainData))
    {
        // do whatever to the string "line"
        //  cout << i + 1 << "  "<< trainData << endl;

        char *pcg = strdup(trainData.c_str());
        //pcg=(char *)malloc(42);
        trainData = strtok(pcg,",");
        i=1;
        while (pcg != NULL)
        {
            int tint=atoi(pcg);
            int tmp[43];

            //printf ("%s",pcg);

            tmp[i]=tint;

            pcg = strtok (NULL, ",");
            //printf("value = %d \n",tmp[i]);
            if (i==5)
            {
              a = tmp[i];   
              printf("value a= %d \n",a); //access this a
            }
            else if(i==6)
            {
              b=tmp[i]; 
              //printf("nilai b = %d \n",b);
            }

            i++;
        }//while pcg
    }

    //   getline(fin, trainData);
}

int main() 
{
  int r;
  LoadConfig();
  // I WANT access from here
  LoadConfig.a = new LoadConfig();
  printf("output fungsi main = %d ",r);
}

1 个答案:

答案 0 :(得分:1)

实现这一目标的最简单方法是从函数中返回 a

int LoadConfig()
{
    int a;
    ...
    return a;
}

int main() 
{   int r;  
    r = LoadConfig();
    printf("output fungsi main = %d ",r);   
}

如果您想要返回多个int,那么一种方法是将您要返回的所有内容封装到classstruct中,然后返回这一点。