我已經編寫了一個程序,以從用戶獲取字符串輸入並將其解析爲令牌並根據輸入移動機器人。我的問題是試圖發佈多個命令。代碼如下所示:爲什麼我的while循環需要新的輸入(C++)
void Navigator::manualDrive()
{
const int bufSize = 42;
char uinput[bufSize];
char delim[] = " ";
char *token;
while(true)
{
Navigator::parseInstruction(uinput);
}
}
/* parseInstruction(char *c) -- parses cstring instructions received
* and moves robot accordingly
*/
void Navigator::parseInstruction(char * c)
{
const int bufSize = 42;
char uinput[bufSize];
char delim[] = " ";
char *token;
cout << "Enter your directions below: \n";
cin.ignore();
cin.getline (uinput, bufSize);
token=strtok(uinput, delim);
if(strcmp("forward", token) == 0)
{
int inches;
token = strtok(NULL, delim);
inches = atoi (token);
Navigator::travel(inches);
}
if(strcmp("back",token) == 0)
{
int inches;
token = strtok(NULL, delim);
inches = atoi (token);
double value = fabs(0.0735 * fabs(inches) - 0.0550);
myRobot.backward(1/*speed*/, value/*time*/);
}
if(strcmp("turn",token) == 0)
{
int degrees;
token = strtok(NULL, delim);
if(strcmp("left",token) == 0)
{
token = strtok(uinput, delim);
degrees = atoi (token);
double value = fabs(0.0041 * degrees - 0.0523);
myRobot.turnLeft(1/*speed*/, value/*time*/);
}
}
if(strcmp("turn",token) == 0)
{
int degrees;
token = strtok(NULL, delim);
if(strcmp("right",token) == 0)
{
token = strtok(uinput, delim);
degrees = atoi (token);
double value = fabs(0.0041 * degrees - 0.0523);
myRobot.turnRight(1/*speed*/, value/*time*/);
}
}
if(strcmp("stop",token) == 0)
{
myRobot.motors(0,0);
}
}
在函數manualDrive中,我有一個while循環無限地調用函數parseInstruction。程序輸出「在下面輸入您的指示:」當我給出程序指令時,它會執行它們,然後再次輸出「在下面輸入您的指示:」,當我再次輸入我的指示時,它不會執行它們並輸出「輸入您的指示下面:「代替。我相信這是一個非常簡單的修復,我只是對C++很陌生。所以,如果你可以請幫助我,並告訴我爲什麼該計劃只採取第一組方向。謝謝
從問題格式的角度來看,我認爲你有一些格式問題。確保在所有代碼行之前加上四個空格。 – 2010-04-12 22:39:52
對不起,我試圖修復它。 – Van 2010-04-12 22:49:15
感謝您解決我的縮進問題 – Van 2010-04-12 23:02:51