Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
有没有办法将sscanf与stdin一起使用?_C_Stdin_Scanf - Fatal编程技术网

有没有办法将sscanf与stdin一起使用?

有没有办法将sscanf与stdin一起使用?,c,stdin,scanf,C,Stdin,Scanf,我有一个程序,它要么从文件中获取数据,要么从标准输入中获取数据。 我编写了使用sscanf扫描文件的代码。 我想知道我是否可以使用stdin而不是scanf重用这些代码 例: 我如何修改它,使其与标准输入一起工作 while(fgets(buffer, MAX_LEN, input) != NULL) { if (sscanf(buffer, "%s %s %s", one, two, three) == 3) { } } fscanf:您不需要更改sscanf()调用-从输入文件

我有一个程序,它要么从文件中获取数据,要么从标准输入中获取数据。 我编写了使用sscanf扫描文件的代码。 我想知道我是否可以使用stdin而不是scanf重用这些代码

例:

我如何修改它,使其与标准输入一起工作

while(fgets(buffer, MAX_LEN, input) != NULL) { 
    if (sscanf(buffer, "%s %s %s", one, two, three) == 3) { } 
}

fscanf:

您不需要更改
sscanf()
调用-从输入文件读取的是
fgets()
调用


通过在
fgets()
调用中将
input
替换为
stdin
stdin
是在
stdio.h
中声明的引用标准输入的全局
文件*

fgets中的第三个参数(缓冲区、最大长度、输入)
即,
input
是获取输入的来源。在您的情况下,应将其替换为
stdin
,以便它从标准控制台而不是文件获取输入。

sscanf从字符*解析数据。所以根本没有文件。您可能希望将stdin读入缓冲区,而不是从某个文件读入缓冲区。请查看可以从stdin读入的fscanf。您可能需要的是
fscanf
,第一个参数将指定数据源。当然,您也可以指定
input=stdin,因为它只是一个指针。开玩笑吧?如果提出问题的人知道如何使用fgets和scanf,那么他们肯定知道如何使用fscanf。他们显然只是不知道它的存在。