从scanf读取换行符

read newline from scanf

本文关键字:换行符 读取 scanf      更新时间:2023-10-16

我试图从stdin输入,使用scanf逐行,但我需要执行一个特定的函数时,只有一个换行符被输入。Scanf似乎不能正确地做这件事,我不能使用fgets,因为程序的其余部分似乎停止工作。帮助吗?

char input[1000];
scanf("%s", input);
if((strcmp(input, "n") == 0) {
// some code
} 

似乎不起作用。我只需要在只有换行符和其他任何东西时实现这一点。由于

可以逐行读取scanf。如果只输入一个新的行字符(例如:当用户按下回车键时,将出现您可以处理的空行。试试这个:

char input[1024];
while (scanf("%1023[^n]n", input) == 1) {
    if (input[0] == '') {
        // handle empty line
        continue;
    }
    // handle non-empty line
}

在这种情况下,输入将始终以空结束,并且不包含'n'。请注意,scanf只允许读取尽可能多的字符作为缓冲区的大小减去空字符在结束。此外,scanf在成功时返回它成功扫描的变量的数量。

使用std::string, std::getlinestd::basic_string::empty,我们可以在循环中运行输入,如果用户只是按enter键而不输入任何文本,我们可以检测到并调用函数。在本例中,如果没有输入任何内容,则结束循环。

void no_input()
{
    std::cout << "You did not enter anything";
}
int main() {
    bool keep_going = true;
    while (keep_going)
    {
        std::string foo;
        std::cout << "Enter command: ";
        std::getline(std::cin, foo);
        if (foo.empty())
        {
            no_input();
            keep_going = false;
        }
    }
}
<<p> 生活例子/kbd>