fscanf 仅读取一个整数但分配给多个变量

fscanf only reading only one integer but assigning to multiple variables

我整天都在做一个项目,但我遇到了麻烦,因为 fscanf 没有按照我认为的方式工作。

我正在读取一个包含如下内容的文件:

AND 0 3 2

这是我的一段代码,它给我带来了问题:

while(fscanf(circuit, "s",cur_gate)!=EOF){
    if(cur_gate[0]=='A'){
            fscanf(circuit,"%d %d %d",&cur_output,&cur_input1,&cur_input2);
            printf("current output: %d\n",cur_output);
            printf("current input: %d current input2: %d\n",cur_input1,cur_input2);

所以我正在做的是读取文件并检查字符串是否 = AND (cur_gate)。然后如果它 = 'A',我正在读取 3 个整数。我想将第一个整数分配给 cur_output,将第二个和第三个整数分别分配给 cur_input1 和 cur_input2。

问题是它的输出是:

当前输出:0

当前输入:0 当前输入2:0

虽然输出实际上应该是:

当前输出:0

当前输入:3 当前输入2:2

老实说,我不知道出了什么问题,因为我之前做了几乎相同的事情并且它起作用了。感谢您的帮助!

fscanf(circuit, "s",cur_gate) 将尝试扫描 文字 s 字符。如果你想扫描一个字符串,你需要像 %s.

这样的东西

如果您遵循 scanf 的 "check for what you want rather than don't want" 规则,这会更加明显:

while (fscanf (circuit, "s",cur_gate) == 1) {

在您的案例中发生的情况是对文字 s 的扫描失败,但不是以 returns EOF 的方式。所以,当你开始扫描整数时(缓冲区必须有一个 A 作为进入 if 循环的第一个字符),它们也会失败,因为输入流指针仍在AAND 的开头。

As an aside, unless you control the input, using fscanf here can lead to buffer overflow problems. There are probably better ways to do it.

试试这个:

while(fscanf(circuit, "%s",cur_gate)!=EOF){
    if(cur_gate[0]=='A'){
            fscanf(circuit,"%d %d %d",&cur_output,&cur_input1,&cur_input2);
            printf("current output: %d\n",cur_output);
            printf("current input: %d current input2: %d\n",cur_input1,cur_input2);

变化:

"s" -> "%s"