为什么这段代码打印“那个命令不存在!当它的打印语句在理论上从未在代码中达到?

问题描述 投票:0回答:0

这是一个简单的 C 程序,可以无限地接受输入,并对给定的输入做出响应。然而,无论给出的输入是什么,程序总是会打印“那个命令不存在!”。我觉得字符串卡在标准输出缓冲区内,但我不确定它是如何到达那里的,因为这行代码永远不应该针对我一直在测试的输入执行(字母 C 和其他字母,你知道,一般调试接受单个字母的程序)。也许这是一个编译问题?

这里是主要代码:

#include <stdio.h> 
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

void commands(char input){
    if(input == 'C'){
        int processPriority;
        printf("%s","Enter the desired priority of the process (0=high, 1=medium, 2=low):");
        scanf(" %d", &processPriority);
        printf("Created a new process with ID %d with %d priority\n", 2, processPriority);
        return;
    }
    printf("%s","That command does not exist!\n");
    return;
}
int main(){
    char buffer;
    while(1){
        //Get user input
        printf("%s","user@OS:~$ ");
        buffer = getchar();

        //Handle the input
        commands(buffer);
    }
}

这是我的 makefile:

main: main.o
    gcc -o main main.o
    
main.o: main.c
    gcc -c -g main.c
clean:
    rm main main.o
c printf stdout
© www.soinside.com 2019 - 2024. All rights reserved.