我正在用C语言编写一个机器人,并且遇到了一个我似乎无法解决的问题。如何获取C中的字符串值?
解决此问题的唯一方法是使用大量goto
语句。 我想找出一种方法来保存自己写超过100个goto
点和语句,如果语句等,我想知道是否有一种方法来获得一个字符串的值。对于示例 -
string Next = "beginning";
goto Next;
beginning:
有什么办法goto
的Next
值,或在Next
的值代入goto
声明?
如果有办法做到这一点,那么无论字符串Next
的值是多少,我都可以为每个驱动命令更改Next
的值,然后goto
。
换句话说,只是将字符串转换为goto
标识符,或者用它来代替它。
感谢您的帮助!
-EDIT-
很多人都建议使用switch语句。我不确定这是否会工作,因为我如何编程。该程序的结构在这里 - 通过这种代码只包含我实际上的一点,我的真实代码已超过500行到目前为止。此外,驾驶指令也大大简化。但基本概念在这里,比我想要的更容易理解。
task main()
{
//integer list
int forwardDrivingSelector = 0;
int backwardDrivingSelector = 0;
int rightRotatingSelector = 0;
string nextCommand;
int waitTime = 0;
int countup = 0;
//driving commands
driveForward:
while(forwardDrivingSelector == 1)
{
motor[leftMotor] = 127;
motor[rightMotor] = 127;
countup++;
wait1Msec(1);
if(countup == waitTime)
{
countup = 0;
goto nextCommand;
}
}
driveBackward:
while(backwardDrivingSelector == 1)
{
motor[leftMotor] = -127;
motor[rightMotor] = 127;
countup++;
wait1Msec(1);
if(countup == waitTime)
{
countup = 0;
goto nextCommand;
}
}
rightRotate:
while(rightRotatingSelector == 1)
{
motor[leftMotor] = 127;
motor[rightMotor] = -127;
countup++;
wait1Msec(1);
if(countup == waitTime)
{
countup = 0;
goto nextCommand;
}
}
//autonomous driving code
//first command, drive forward for 1000 milliseconds
forwardDrivingSelector = 1;
nextCommand = "secondCommand";
waitTime = 1000;
goto driveForward;
secondCommand:
forwardDrivingSelector = 0;
//second command, rotate right for 600 milliseconds
rightRotatingSelector = 1;
nextCommand = "thirdCommand";
waitTime = 600;
goto rightRotate;
thirdCommand:
rightRotatingSelector = 0;
//third command, drive backwards for 750 milliseconds
backwardDrivingSelector = 1;
nextCommand = "end";
waitTime = 750;
goto driveBackward;
end:
backwardDrivingSelector = 0;
}
等等。这是如何工作的。 我有一个整数列表,包括驱动命令选择器,countup和waitTime整数,以及我正在讨论的字符串nextCommand。 接下来是驱动命令。在我的真实代码中,我有大约30条命令,并且它们都连接到遥控器,并且它的驱动命令超过400行。 接下来是自治代码。我这样设置它的原因是,自治代码部分将会简短,简单并且重要。相当多的命令添加到驱动代码,您打开选择,告诉nextCommand字符串中的下一个命令是什么,设置WAITTIME(这是多长的命令,以毫秒为单位),然后你让代码转到你输入的驾驶命令。驾驶命令驱动你放入的时间量,然后执行next命令;
这是否有一种方法,使goto语句“解释”的字符串作为一个标识符,它是可以改变一切理论上的工作。
大约有4个简单的方法,我能想到的,现在,可以让过去,这很容易,但它们会使代码真的很长,凌乱。
既然您对我的问题有更好的理解,那么还有其他意见吗? :)
顺便说一句 - 我正在使用一个名为robotC的程序,我正在编写一个vex机器人。所以我必须使用纯,基本,C,和我不能使用任何插件或任何东西......这是另一个原因,这是复杂的,因为我不能有多个类和类似的东西...
有一定是更好的方法做你比100级的goto做什么... – Mysticial 2012-01-09 03:17:28
什么实际问题? – 2012-01-09 03:18:24
如果你能描述根本问题,有人可能会发现比这些'goto's更好的方法 – Kevin 2012-01-09 03:20:08