【问题标题】:fscanf only reading only one integer but assigning to multiple variablesfscanf 只读取一个整数但分配给多个变量
【发布时间】:2015-11-04 04:33:46
【问题描述】:

我整天都在处理一个项目,但由于 fscanf 没有按照我想象的方式工作,所以我陷入了困境。

我正在读取一个包含类似内容的文件:

与 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

老实说,我不知道出了什么问题,因为我之前做过几乎同样的事情,而且效果很好。感谢您的帮助!

【问题讨论】:

    标签: integer eof scanf


    【解决方案1】:

    fscanf(circuit, "s",cur_gate) 将尝试扫描 literal s 字符。如果你想扫描一个字符串,你需要%s之类的东西。

    如果你遵循scanf 的“检查你想要的东西而不是不想要的东西”规则,这会更明显:

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

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

    顺便说一句,除非你控制输入,否则在这里使用fscanf 会导致缓冲区溢出问题。大概有better ways来做吧。

    【讨论】:

    • 谢谢!我不敢相信我没听懂。我太专注于 while 循环的内部,以至于忽略了这一点。如果你不能说我是个菜鸟。谢谢
    • @Ryan,我们曾经,但对于我们这些老屁来说,有时很难回忆起 :-)
    【解决方案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);
    

    变化:

    "s" -> "%s"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-06
      • 2017-07-02
      • 1970-01-01
      • 2021-10-12
      • 2015-03-21
      • 2016-09-23
      • 1970-01-01
      相关资源
      最近更新 更多