[(C)scanf在终止值为[^ \ n]时不起作用

问题描述 投票:-1回答:1

我正在创建一个程序,您可以在其中通过该程序执行终端命令。我想访问目录(使用cd / Users / user / Desktop),但是由于scanf在空白处终止,因此我不得不将终止值更改为[^\n]。那是当错误弹出时。每当我输入命令时,它都会执行该命令,但是下一次程序进入(无限)循环时,它不会停止执行scanf函数之前的行。当终止值为%s时,这没有发生。这是程序的代码:

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

void execute(){
    char* command = (char *) malloc(15);
    char* output = (char *) malloc(4096);
    printf(">> ");
    scanf("%[^\n]", command);            //Here is the scanf function
    FILE* cmd = popen(command, "r");
    fread(output, sizeof(output), 32000, cmd);
    if (strlen(output) != 0){
        printf("\n%s\n", output);
    }
    free(output);
    pclose(cmd);
}

int main(){
    while (1){
        execute();
    }
}

这里是终止值为[^\n]时的输出:

>> ls

Applications
Desktop
Documents
//Here the rest of the contents in my user folder appear (twice for some reason, that's also an issue related to this).

>> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> 
>> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> 
>> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> 
>> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> 
// This then goes on forever

这里是终止值为%s时的输出:

>> ls

Applications
Desktop
Documents
//Here the rest of the contents in my user folder appear (once)

>> //Here I can input things again

有人可以教我如何解决这个问题吗? (我尝试过gets(),结果相同)

c scanf
1个回答
2
投票

由于您正在告诉scanf不要读取\n,因此它将其保留在stdin中,因此,当循环重复时,它仍然存在,并导致下一次迭代立即返回一个空字符串。要解决此问题,有几种选择:

© www.soinside.com 2019 - 2024. All rights reserved.