C:使用scanf的方法

Val*_*lva 1 c io input scanf

我可以scanf(...)用作函数的参数吗?像这样:

printInteger(scanf(....));
Run Code Online (Sandbox Code Playgroud)

我可以使用scanf将我读取的值归因于某个变量吗?像这样:

n = scanf(...);
Run Code Online (Sandbox Code Playgroud)

ps:我在这里解释为什么我这么问.

我知道这个问题可能有点奇怪,但我正在开发一个项目,它正在开发一个编译器,它将一些语言作为输入,然后编译为C.

例如,这是我的语言,我们称之为'stackoverflow';)

proc printInteger(integer k)
    integer i;
        begin
            for i = 1 to k do
                print i;
        end

proc main()
    integer n, i;
    boolean ok;
    begin
        printInteger(getInteger);
        n = getInteger;
        ok = true;
        while i < n do
            begin
                print i;
                i = i + 1;
            end
        if ok then print 1; else print 0;
    end
Run Code Online (Sandbox Code Playgroud)

我不会深入学习语言,但请注意,这getInteger意味着我想做一个scanf(...),我的意思是,当getInteger我想要编译时scanf(...),这就是为什么我想知道一些使用方法scanf(...).

pb2*_*b2q 5

我可以使用scanf(...)作为函数的参数吗?像这样:

是PrintInteger(scanf的(....));

我可以使用scanf将我读取的值归因于某个变量吗?像这样:

n = scanf(...);

可以使用scanf函数作为参数,但两个问题的真正答案是否:scanf 返回任何扫描的数据,它返回成功扫描的项目 - 或者EOF是否在任何成功之前达到输入结束扫描.您只能使用作为scanf参数传递的指针访问扫描的项目以接收值.因此,尽管你可以通过scanf作为参数传递给一个函数,它不会做你似乎什么希望.

如果你想getInteger用你的语言实现操作,在C中,很难提出建议,因为只有你知道这种语言/操作应该如何工作.只是使用scanf,实现看起来像这样:

int nextInt;
int numScanned = scanf("%d", &nextInt);

if (numScanned < 1)
    handleError();
return nextInt;
Run Code Online (Sandbox Code Playgroud)

但是如果你正在为你的语言做一般的解析,那么使用scanf是一个坏主意:你很快会遇到问题的局限性scanf,除非你的语言,否则你无法预测所有的输入类型是非常简单的,比你已经包括了例如简单.

要做到这一点,找一个好的lexC库.这样可以防止很多麻烦.否则,如果你必须自己做lexing,开始查看fgets,从你的输入一次获得一行,并自己做标记.