c - 将整个代码块转换为 C 中的一行

标签 c

<分区>

例如,我想将整个代码块输入到命令中:

int k = 0;

for (k = 0; k < 50; k++) 
{
    sprintf(buf, "M LR 10 -10\n");                     //We put the string "M L 10" into the string buffer.
    write(sock, buf, strlen(buf));                     //We send the buffer into the socket.
    memset(buf, 0, 80);                                //Clear the buffer, set buffer to value 0.
    read(sock, buf, 80);                               //Read from the socket to get the results.
    int lme, rme;
    sprintf(buf, "S MELR\n");                          //sensor command to find ME values
    write(sock, buf, strlen(buf));                     //sends the buffer to the socket
    memset(buf, 0, 80);                                //Clear the buffer, set buffer to value 0.
    read(sock, buf, 80);                               //read from socket to get results.
    sscanf(buf, "S MELR %i %i\n", &lme, &rme);         //takes lme and rme values from results
    printf(buf, "%3i   %-4i\n", lme, rme);
    //distance = 2 * (22/7) * r
}

for (k = 50; k < 51; k++) 
{
    sprintf(buf, "C RME\n");                           //We put the string "C RME" into the string buffer to reset.
    write(sock, buf, strlen(buf));                     //We send the buffer into the socket.
    memset(buf, 0, 80);                                //Clear the buffer, set buffer to value 0.
    read(sock, buf, 80);                               //Read from the socket to get the results.
}

这使我能够更改 {sprintf(buf, "M LR 10 -10\n");} 中字符串的值,即 10-10,剩下的过程自行执行:

例如主代码中的set_motor_speed(10 -10\n)会执行整个功能,如何实现呢?

最佳答案

正如其他人所说:您可以在 C 语言书籍中阅读此类内容,但嘿,我们很好:

set_motor_speed(int a, int b) {
    ...
    for(k = 0; k < 50; k++) {
        sprintf(buf, "M LR %i %i\n", a, b);
        ...
    }
    ...
}

set_motor_speed(10, -10);
set_motor_speed(5, -5);

关于c - 将整个代码块转换为 C 中的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14877000/

相关文章:

c - 新手C指针问题

c - 用户的预期输入是 3 个字符串,但如果用户只给出 2 个字符串,那么我希望我的代码继续进行

c - SIGSEGV,(貌似)由 printf 引起

c - "__builtin_va_list"是如何实现的?

c - 错误返回不兼容指针不兼容 C

c - 确保两个进程交错

python - 优化sympy生成的代码

c - 指向结构内部结构的 void 指针

c++ - 用于确定机器字节顺序的条件预处理器指令

c - c中的匿名流