C ++:从函数访问主变量的最简单方法? [英] C++: Easiest way to access main variable from function?

查看:161
本文介绍了C ++:从函数访问主变量的最简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在处理一个在main()中初始化的字符串,如果我尝试使它成为全局的话,那么它由于某种原因而变得怪异(它变成了一串非字符)。我想知道我是否可以在程序中声明一个函数来访问这个变量......函数本身只能在main或main调用的函数中执行,但编译器在main()之前不会看到变量名称,



以下是相关代码的简要版本:

  string getCommand(int input_pos,string inputstring)
{
int temp_paren = 0;
int begin_pos = stdinstring.rfind((,input_pos);
int len = 0;
while(temp_paren> 0& len< 10)
{
if(stdinstring.substr(begin_pos + len,1)==(){temp_paren ++;}
if(stdinstring.substr(begin_pos + len,1)==)){temp_paren - ;}
len ++;
}
return stdinstring.substr(begin_pos,len);
}

int main(void){

string stdinstring =;
}

我已经考虑前向声明,每次使用它时我们都会用变量传递给函数,甚至让一个类来保存这个变量......解决这个问题最简单的方法是什么?理想情况下,我会有足够的时间使它成为一个全局变量,并找出哪里/为什么会出错,但我只需要完成这一点。感谢您的任何和所有帮助。






编辑:对于任何感兴趣的人:如果我尝试使字符串成为全局字符,就会发生这种情况。所有字符becom e(不知道是否可以看到)






编辑编辑:好的,这里有一个我的代码更完整的版本。此外,我试图粘贴上面的符号是什么似乎是0 0 0 1(ASCII字符代码?)的框?

 #包括<&的iostream GT; 
#include< cstdio>
#include< cstring>
#include< cstdlib>
#include< cmath>
#include< stdint.h>
//#include< regex>

#define PI M_PI
#define VERBOSE 1
using namespace std;

字符串stdinstring;

模板< class dataclass>
struct linkm {
dataclass value;
linkm * next;
};

模板< class dataclass>
class linklist
{
public:
linklist()
{top = NULL;}
〜linklist()
{}
void push(dataclass num)
{
linkm< dataclass> * temp = new linkm< dataclass>;
temp-> value = num;
temp-> next = top;
top = temp;

dataclass pop()
{
if(top == NULL)
return 0;
linkm< dataclass> * temp;
temp = top;
dataclass值;
value = temp-> value;
top = temp->下;
删除temp;
返回值;

bool isEmpty()
{
if(top == NULL)
return 1;
返回0;
}
private:
linkm< dataclass> *最佳;
};

double evaluateExpression(字符串表达式)
{
//示例表达式:(*(/ a 1)(+ b 2))
if(expression.substr (0,2)==(+){cout<<add found<< endl;;
else if(expression.substr(0,2)==( - ){cout <<sub found< lt; endl;}
else if(expression.substr(0,2)==(*){cout<<mult found << endl ;;
else if(expression.substr(0,2)==(/){cout<<div found<< endl;;
else if(expression.substr(0,2)==(sin){cout<<sin found< endl;}
else if(expression.substr(0,2) ==(cos){cout <<cos found<< endl;;
else {cout<"Error:invalid operation;} // //它只是一个数字?
}

字符串getCommand(int input_pos,字符串输入字符串)
{
int temp_paren = 0;
int begin_pos = stdinstring.rfind( (,input_pos);
int len = 0;
while(temp_paren> 0& len< 10)
{
if(stdinstring.substr(begin_pos + len,1)==(){temp_pa如果(stdinstring.substr(begin_pos + len,1)==)){temp_paren--;}
len ++;
}
return stdinstring.substr(begin_pos,len);
}

class symContainer
{
public:
string index [500];
浮点值[500];
int currindex;

symContainer(){currindex = 0; }

void add(string id,float invalue)
{
index [currindex] = id;
值[currindex] = invalue;
currindex ++;
}

float get(string id)
{
int i = 0;
while(i< currindex)
{
if(id == index [i]){return value [i];}
i ++;
}
cout<< 输入无效 - 请求未分配的符号:<< id<< ENDL;
exit(2);
}

};


struct transform {int type;双重论点[4]; };
struct point {double x; double y; };
struct drawing {linklist< point>点;链表<变换>转变; void applyTransforms(linklist< transform> * trsptr){}};
结构组:public drawing {linklist< int>图纸; void transform(linklist< transform> * trsptr){}};
struct symbol {string index; double value;};

char getNext(){//查找函数。有硬过滤器,如用空格替换换行符/制表符
char temp = getchar();
if(temp =='\\\
'){temp ='';}
if(temp =='\t'){temp ='';}
return temp ;


int main(void){

stdinstring =a;

char命令[20],args [2048];
int commandindex = 0; //'我'为我们在
int stdinsize = 2;
double argsArray [8];
bool filled = 0;
int parenlevel = 0;
symContainer符号;

// 1是将在每个循环结束时写入的字符。 0和2分别是前/后1个字符,分别是
char c_lookaround [2];
c_lookaround [0] = NULL;
c_lookaround [1] = getNext();
c_lookaround [2] = getNext();

unsigned long i = 0;

bool write = 0;
while(c_lookaround [2]!= EOF)
{
write = 1;
//查看逻辑在这里。 (清除重复的空格,换行符等)

while(c_lookaround [1] ==''&& c_lookaround [2] ==''){c_lookaround [2] = getNext( );}
while(c_lookaround [0] =='('&& c_lookaround [1] ==''){c_lookaround [1] = c_lookaround [2]; c_lookaround [2] = getNext() ;}
while(c_lookaround [1] ==''&& c_lookaround [2] ==')'){c_lookaround [1] = c_lookaround [2]; c_lookaround [2] = getNext();}
while(c_lookaround [0] == NULL&& c_lookaround [1] ==''){c_lookaround [1] = c_lookaround [2]; c_lookaround [2] = getNext();}
// while(c_lookaround [0] ==')'&& c_lookaround [1] ==''&& c_lookaround [2] =='('){c_lookaround [1] = c_lookaround [2]; c_lookaround [2] = getNext();}
// while(c_lookaround [0] ==')'&& c_lookaround [1] ==''&& c_lookaround [2] =='\0'){cout <<aa; c_lookaround [1] = c_lookaround [2]; c_lookaround [2] = getNext();}

if(c_lookaround [0] =='('&& c_lookaround [1] ==':'&&c_lookaround [2] =='=')
{
getCommand(i,stdinstring);
}

//确定当前圆括号级别
if(c_lookaround [1 ] =='('){parenlevel ++;}
if(parenlevel == 0){write = 0;}
if(c_lookaround [1] ==')'){parenlevel--;}

//写入字符
if(write){stdinstring.push_back(c_lookaround [1]);}
cout
//提前录音!
i ++;
c_lookaround [0] = c_lookaround [1];
c_lookaround [1] = c_lookaround [2];
c_lookaround [2] = getNext();
}

stdinsize = i;

}

解决方案

如果您从<$ c $调用 getCommand() c> main()你应该能够传递变量。
$ b

  int main(void) {
string stdinstring =;
string answe r = getCommand(0,stdinstring);



$ b

如果你调用 getCommand()从其他地方你必须从 main(),然后到 getCommand()。你也应该能够使它成为全球性的,但没有代码我不知道你为什么不能。

  // stdinstring =a在这种情况下(这是如何设置为除了它之外的任何内容?
string getCommand(int input_pos,string inputstring)
{
int temp_paren = 0; $ b $ (int temp_paren> 0& len< 10)// int begin_pos =没有(所以循环终止与len = 10
{
if(stdinstring.substr(begin_pos + len,1)==(){temp_paren ++;}
if(stdinstring .substr(begin_pos + len,1)==)){temp_paren--;}
len ++;
}
返回stdinstring.substr(begin_pos,len); //返回前十个字符串字符串,它将是a
}


I'm currently dealing with a string initialized in main() that for some reason freaks out (it becomes a string of non-characters) if I try and make it global. I'm wondering whether I can have a function declared in the program access this variable... the function itself will only ever be executed in main or functions called from main, but the compiler doesn't see the variable name until main() is reached.

Here is a skinny version of the relevant code:

string getCommand(int input_pos,string inputstring)
{
int temp_paren=0;
int begin_pos = stdinstring.rfind("(",input_pos);
int len = 0;
while (temp_paren>0 && len < 10)
 {
 if (stdinstring.substr(begin_pos+len,1)=="(") {temp_paren++;}
 if (stdinstring.substr(begin_pos+len,1)==")") {temp_paren--;}
 len++;
 }
 return stdinstring.substr(begin_pos,len);
}

int main(void) {

string stdinstring = ""; 
}

I've been considering forward declarations, passing the variable to the function by hand each time I use it, even making a class to hold that variable... What would be the simplest way to solve this problem? Ideally I would have enough time to make it a global variable and figure out where/why that's going wrong, but I just need to get this done. Thanks for any and all help.


EDIT: For anyone interested: This is what happens if I try and make the string a global. All of the characters become "" (dunno if that's even visible)


EDIT EDIT: Okay, here's a more complete version of my code. Also, the symbols I tried pasting above were boxes with what appeared to be "0 0 0 1" (ASCII character code?)

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<stdint.h>
//#include<regex>

#define PI M_PI
#define VERBOSE 1
using namespace std;

string stdinstring; 

template <class dataclass> 
struct linkm {
  dataclass value;
  linkm *next;
};

template <class dataclass> 
class linklist 
{
  public:
    linklist()
      {top = NULL;}
    ~linklist() 
      {}
    void push(dataclass num)
      {
      linkm<dataclass> *temp = new linkm<dataclass>;
      temp->value = num;
      temp->next = top;
      top = temp;
      } 
    dataclass pop()
      {
      if (top == NULL) 
        return 0;
      linkm<dataclass> * temp;
      temp = top;
      dataclass value;
      value = temp->value;
      top = temp->next;
      delete temp;
      return value;
      }
    bool isEmpty()
      {
      if (top == NULL) 
        return 1;
      return 0;
      }
  private:
    linkm<dataclass> *top; 
};

double evaluateExpression(string expression)
{
// sample expression : (* (/ a 1) (+ b 2))
     if (expression.substr(0,2)=="(+") {cout << "add found"<<endl;}
else if (expression.substr(0,2)=="(-") {cout << "sub found"<<endl;}
else if (expression.substr(0,2)=="(*") {cout << "mult found"<<endl;}
else if (expression.substr(0,2)=="(/") {cout << "div found"<<endl;}
else if (expression.substr(0,2)=="(sin") {cout << "sin found"<<endl;}
else if (expression.substr(0,2)=="(cos") {cout << "cos found"<<endl;}
else {cout << "Error: invalid operation";} // or is it just a number?
}

string getCommand(int input_pos,string inputstring)
{
int temp_paren=0;
int begin_pos = stdinstring.rfind("(",input_pos);
int len = 0;
while (temp_paren>0 && len < 10)
 {
 if (stdinstring.substr(begin_pos+len,1)=="(") {temp_paren++;}
 if (stdinstring.substr(begin_pos+len,1)==")") {temp_paren--;}
 len++;
 }
 return stdinstring.substr(begin_pos,len);
}

class symContainer
{
public:
string index[500];
float value[500];
int currindex;

symContainer () { currindex = 0 ; }

void add(string id,float invalue)
{
index[currindex] = id;
value[currindex] = invalue;
currindex++;
}

float get(string id)
{
int i=0;
while (i<currindex)
 {
 if(id==index[i]) {return value[i];}
 i++;
 }
 cout << "Invalid input - an unassigned symbol was requested:" << id << endl;
 exit(2);
}

};


struct transform { int type; double arguments[4]; } ;
struct point { double x; double y; } ;
struct drawing { linklist<point> points; linklist<transform> transforms; void applyTransforms(linklist<transform> * trsptr) {}  } ; 
struct group : public drawing { linklist<int> drawings; void transform(linklist<transform> * trsptr) {} } ;
struct symbol {string index; double value;};

char getNext() { //for the lookaround function. has hard-filters, like replacing newlines/tabs with spaces
char temp = getchar(); 
if (temp=='\n') {temp=' ';}
if (temp=='\t') {temp=' ';}
return temp;
}

int main(void) {

stdinstring="a";

char command[20], args[2048];
int commandindex=0;     //'i' for what command we're on
int stdinsize=2;
double argsArray[8];
bool filled=0;
int parenlevel = 0;
symContainer symbol;

//1 is the character that will be written at the end of each loop. 0 and 2 are 1 char ahead/behind, respectively
char c_lookaround[2]; 
c_lookaround[0]=NULL;
c_lookaround[1]=getNext();
c_lookaround[2]=getNext();

unsigned long i=0;

bool write=0;
while( c_lookaround[2] != EOF )
{ 
write=1;
// Lookaround logic goes here. (Clearing duplicate whitespaces, newlines, and the like)

while (                         c_lookaround[1]==' '  && c_lookaround[2]==' ' ) {c_lookaround[2]=getNext();}
while (c_lookaround[0]=='('  && c_lookaround[1]==' '                          ) {c_lookaround[1]=c_lookaround[2]; c_lookaround[2]=getNext();}
while (                         c_lookaround[1]==' '  && c_lookaround[2]==')' ) {c_lookaround[1]=c_lookaround[2]; c_lookaround[2]=getNext();}
while (c_lookaround[0]==NULL && c_lookaround[1]==' '                          ) {c_lookaround[1]=c_lookaround[2]; c_lookaround[2]=getNext();}
//while (c_lookaround[0]==')'  && c_lookaround[1]==' '  && c_lookaround[2]=='(' ) {c_lookaround[1]=c_lookaround[2]; c_lookaround[2]=getNext();}
//while (c_lookaround[0]==')'  && c_lookaround[1]==' '  && c_lookaround[2]=='\0' ) {cout<<"aa";c_lookaround[1]=c_lookaround[2]; c_lookaround[2]=getNext();}

if (c_lookaround[0]=='('  && c_lookaround[1]==':'  && c_lookaround[2]=='=') 
 {
    getCommand(i,stdinstring);
 }

//Determine current parentheses level
if (c_lookaround[1] == '(') { parenlevel++;}
if (parenlevel==0) {write=0;}
if (c_lookaround[1] == ')') { parenlevel--;}

//Write the character 
if (write) {stdinstring.push_back(c_lookaround[1]);}
cout << stdinstring<< endl;

//Advance the tape!
i++;
c_lookaround[0]=c_lookaround[1];
c_lookaround[1]=c_lookaround[2];
c_lookaround[2]=getNext();
}

stdinsize = i;

}

解决方案

if you're calling getCommand() from main() you should be able to pass the variable.

int main(void) {
    string stdinstring = ""; 
    string answer = getCommand(0, stdinstring);
}

If you are calling getCommand() from somewhere else you'll have to pass the variable to that function from main() and then to getCommand(). Also you should be able to make it global but without the code I don't know why you weren't able to.

//stdinstring = "a" in the case (how is this set to anything but it?
string getCommand(int input_pos,string inputstring)
{
   int temp_paren=0;
   int begin_pos = stdinstring.rfind("(",input_pos); //This equals -1 
   int len = 0;
   while (temp_paren>0 && len < 10) //There is no ( so the loop terminates with len=10
   {
      if (stdinstring.substr(begin_pos+len,1)=="(") {temp_paren++;}
      if (stdinstring.substr(begin_pos+len,1)==")") {temp_paren--;}
     len++;
   }
   return stdinstring.substr(begin_pos,len); //returns the first 10 chars of stdinstring which would be "a"
}

这篇关于C ++:从函数访问主变量的最简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆