首页 > 解决方案 > Printf 中的额外 \1 个字符

问题描述

我正在开发一个 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在上一行之后插入的,但我根本不知道是什么原因造成的!

为了清楚起见,我提供了一个屏幕截图: 在此处输入图像描述

这是整个循环:

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()行为不端之一是正确的。

标签: cformattingprintf

解决方案


推荐阅读