C++: Easiest way to access main variable from function?

吃可爱长大的小学妹 提交于 2019-12-02 08:51:56

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"
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!