Printf中的额外\ 1字符

时间:2018-10-23 00:19:59

标签: c formatting printf

我正在研究一个C程序来解决餐厅哲学家的问题。我循环遍历500个哲学家的状态变化,并通过以下语句输出每个哲学家的状态:

printf("  %d> |%s|%s|%s|%s|%s \n", i, get_state(phils[0]), get_state(phils[1]), get_state(phils[2]), get_state(phils[3]), get_state(phils[4]));

对于上下文,这是函数get_state,该函数将数字哲学家的身份转换为字符串:

char * get_state(int t) {
    if (t == 1)
        return "  Thinking   ";
    if (t == 2)
        return "   Hungry    ";
    if (t == 3)
        return "   Eating    ";
    return "----Error----";
}

我的问题是:每5到30行,其中一行将以Unicode字符U+0001开头。看来它可能是在前一行的\n之后插入的,但我根本无法确定是什么原因造成的!

为了清晰起见,我提供了一个屏幕截图: enter image description here

这是整个循环:

for (i = 1; i <= MAX; i++) {
    silent = 0;
    // receive message from child node
    for (j = 0; j < PHIL_NO; j++) {
        if(phils[j] == EATING) {
            count[j]++;
        }
        lastPhils[j] = phils[j];
    };
    read(host[READ], &msg, sizeof(msg));
    phils[msg.index] = msg.state;


    for (j = 0; j < PHIL_NO; j++) {
        if (phils[j] == lastPhils[j]) 
        {
            silent++;
        }
    };

    printf("%4d> |%s|%s|%s|%s|%s \n", i, get_state(phils[0]), get_state(phils[1]),
            get_state(phils[2]), get_state(phils[3]), get_state(phils[4]));


    // if message is "hungry"
    if (msg.state == HUNGRY) {
        state_left = 0;
        state_right = 0;
        // check if chopsticks are available

        if (phils[(msg.index - 1)%PHIL_NO] == EATING) {
            state_left = 1;
        }

        if(phils[(msg.index + 1)%PHIL_NO] == EATING) {
            state_right = 1;
        }
        // if available...
        if (state_left+state_right == 0) {
            // send message EATING to node
            msg.state = EATING;
            write(node[msg.index][WRITE], &msg, sizeof(msg));
        } else {
            // make the node wait
            write(node[msg.index][WRITE], &msg, sizeof(msg));
        }
    } else if (msg.state == THINKING) {
        // awake neighborhood nodes to eat
        write(node[(msg.index-1)%PHIL_NO][WRITE], &msg, sizeof(msg));
        write(node[(msg.index+1)%PHIL_NO][WRITE], &msg, sizeof(msg));

    }
};

编辑:奇怪的是,当我在XTerm中运行它时,我看不到多余的字符。我认为这只是意味着XTerm不显示它。在这一点上,我可以肯定@Barmar假设它是我的管道write()行为异常之一是正确的。

0 个答案:

没有答案