我根本不知道出了什么问题。我有一个 while 循环(代码块 1),它在循环的一次迭代后立即终止。我什至已经注释掉了整个 switch 语句,所以只有printf(...)
andscanf(...)
保留,并且循环似乎终止了。
循环:
int main(int argc, char *argv[]) {
if(argc != 2) {
printf("Usage requires hostname\n");
return 1;
}
TCPClient client;
char str[1];
unsigned char buf[BUFLEN];
bool run = true;
printf("The commands in use are:\n"
"h - help\n"
"r - read ENCs (incremental)\n"
"x - exit\n");
while(run) {
printf("Enter a command: ");
scanf("%s", str);
switch(str[0]) {
case 'h':
printf("The commands in use are:\n"
"h - help\n"
"r - read ENCs (incremental)\n"
"x - exit\n");
break;
case 'r':
client.recvData(argv[1], buf, BUFLEN);
for(int i = 0; i < BUFLEN / 4; i++) {
if(i % 3 == 0)
printf("\n");
printf("Encoder %d: %d\t", i, (int)((((buf[4 * i] << 24) | (buf[4 * i + 1] << 16)) | (buf[4 * i + 2] << 8)) | (buf[4 * i + 3])));
}
printf("\n");
break;
case 'x':
run = false;
break;
default:
printf("Unrecognized command\n");
break;
}
}
return 0;
}
在某一时刻,我添加了
if(run)
printf("run = true");
在 while 循环之后查看它是否由于控制 bool ( run
) 为假而中断。结果是没有输出,说明不知何故,run
变成了假。无论输入是什么,或者即使 switch 语句消失,都会发生这种情况,在这种情况下,什么都不应该run
成为错误。
真正奇怪的是,在另一个文件中,我有一个类似的循环,但它确实有效:
void *control(void *arg) {
DAC dac(5);
char str[1];
int chan = -1;
uint16_t code = -1;
while(run) {
printf("Enter a command: ");
scanf("%s", str);
switch(str[0]) {
case 'h':
printf("The commands in use are:\n"
"h - help\n"
"s - set DACs\n"
"r - read ENCs (incremental)\n"
"t - read ENCs (cumulative)\n"
"q - Toggle the quadrature waveform\n"
"x - exit\n");
break;
case 's':
chan = code = -1;
printf("Enter the DAC channel: ");
scanf("%d", &chan);
printf("Enter the value: ");
scanf("%hu", &code);
pthread_mutex_lock(&lock);
dac.setDAC(chan, code);
pthread_mutex_unlock(&lock);
break;
case 'r':
pthread_mutex_lock(&lock);
for(int i = 0; i < BUFLEN; i++) {
if(i % 3 == 0)
printf("\n");
printf("Encoder %d: %d\t", i, incBuf[i]);
incBuf[i] = 0;
}
printf("\n");
pthread_mutex_unlock(&lock);
break;
case 't':
pthread_mutex_lock(&lock);
for(int i = 0; i < BUFLEN; i++) {
if(i % 3 == 0)
printf("\n");
printf("Encoder %d: %ld\t", i, cumBuf[i]);
}
printf("\n");
pthread_mutex_unlock(&lock);
break;
case 'q':
runSignal = !runSignal;
if(runSignal)
printf("Quadrature waveform enabled\n");
else
printf("Quadrature waveform disabled\n");
break;
case 'x':
run = false;
break;
default:
printf("Unrecognized command\n");
break;
}
}
dac.reset();
pthread_exit(NULL);
}
我对正在发生的事情感到很迷茫......