是否可以使用scanf仅检测新行输入?

时间:2018-11-15 18:49:30

标签: c

我想重现终端用户的行为,并尽可能使用scanf

当用户仅输入新行时,终端将继续打印目录,直到插入真实命令为止。 插入新行时,函数scanf的正常行为是保持跳空行等待用户真正插入有效字符。

观察:当我执行./main.out时,此终端模拟正在运行,这意味着我不是在谈论我的OS终端,而是在我的程序中谈论一个用C语言模拟的终端。

scanf插入空白行时通常会发生什么:

realPC:~/realDirectory$ ./main.out //starting our simulated terminal
pc:~/Desktop$ '\n'
'\n'
'\n'
"COMMAND\n"         //PROCESS THE COMMAND!
pc:~/Desktop$       //waiting...

我想要什么:

realPC:~/realDirectory$ ./main.out //starting our simulated terminal
pc:~/Desktop$ '\n'
pc:~/Desktop$ '\n'
pc:~/Desktop$ '\n'
pc:~/Desktop$ "COMMAND\n" //Process the command here
pc:~/Desktop$             //waiting...

此目录仅是一个示例,我想打印任何消息(例如,在空输入后继续打印箭头">>>"),问题是scanf似乎根本没有考虑{ {1}}输入,所以我什么也不能打印

我知道'\n'可以代替scanf,但是我想知道是否可以使用scanf函数(我不习惯fget,我也接受其他解决方案,如果可能)

这是代码(fgets(userInput, 1024, stdin)不能同时用于两种用途)

scanf

很显然,当我说用户键入int main() { char userInput[1024]; char pwd[] = "pc:~/marcospb19"; // Directory that keeps being printed while (1) { printf("%s$ " , pwd); // Print the directory just like terminals do scanf(" %s" , userInput); // I wanted this to enter the while and keep printing directory while (userInput[0] == '\n') // Keeps the input inside the loop, if is a new line { puts("We're inside this loop! that's good, now keep printing directory..."); printf("%s$ " , pwd); // Directory printed, next: take input again scanf(" %s" , userInput); // This should be able to receive '\n'. // This loop should continue if user types '\n' } // Now, you can process the input, it isn't empty! printf("Process the input: %s\n", userInput); } } 时,他只是按下Enter键(不是真正地键入)。

2 个答案:

答案 0 :(得分:2)

  

是否可以使用scanf仅检测新行输入?

  char eol[2];
  if (scanf("%1[^n]", eol) == 1) {
    puts("Input with just new line");
  else {
    // read the line via other means
  }

scanf()并尝试读取用户输入的的问题包括:

  • 难以对宽度限制进行编码。
  • 需要在该行的前一部分之后消费"\n"
  • 仅在"\n"输入中很难。

  

我不习惯fgets

比编写一些替代方法更好的是,学会使用标准库棚中的最佳工具来读取

答案 1 :(得分:1)

scanf rapidly gets complicated,因为它会将阅读输入与处理输入混合在一起。当您只想阅读一行并对其进行操作时,fgets更合适。阅读该行,然后根据需要进行处理。您甚至可以使用sscanf来保留scanf家族。

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

int main()
{
    char userInput[1024];
    char pwd[] = "pc:~/marcospb19"; // Directory that keeps being printed

    printf("%s$ " , pwd);
    while (fgets(userInput, sizeof(userInput), stdin) != NULL)
    {
        if( strcmp(userInput, "\n") == 0 ) {
            puts("Empty input.");
        } 
        else {
            puts("Some input");
        }

        printf("%s$ " , pwd);
    }

    puts("");
}

这也使您可以进行更复杂的处理,例如查找空白行。

    if( strspn(userInput, " \t\r\n") == strlen(userInput) ) {
        puts("Blank input.");
    }

请注意,fgets会将换行符留在最后,因此您可能必须先删除userInput的换行符。

相关问题