【问题标题】:fscanf function not workingfscanf 功能不工作
【发布时间】:2014-09-13 23:18:49
【问题描述】:

我目前正在编写一个程序,它从文本文件中的 2 个数字集合中读取数字并将它们打印出来。我想稍后使用这些数字来确定 GCD,但我必须能够先从文件中扫描它们。文本文件如下所示:

24      72
25      50
31      89
...

在第一行的每个数字和第二行的每个数字之间按下制表符。

到目前为止我已经想出了这个(注释掉的部分将用于确定 GCD):

/*
File name: euclid.cpp
This program find the largest common multiple of two numbers using the Euclid  method.
*/

#include <stdio.h>
#include "genlib.h"
#include "simpio.h"

int main()
{
    FILE *input;
    long num1=0, num2=0, orinum2=0, rem=0, gcd=0;
    int i=0, size=0;
    char temp;

    input=fopen("Euclid.txt", "r"); 

    while((temp=getc(input))!=EOF)
    {
        if(temp=='\n') size++;
    }
    size++;

    while(i<size)
    {
        fscanf(input, "%d\t%d%[^\n]", &num1, &num2);
        printf("%d\t%d\n", num1, num2);
        orinum2=num2;
/*      while (true)
        {
            rem=num1%num2;
            if (rem==0)
            {
                gcd=num2; break;
            }
            else
            {
                num1=num2;
                num2=rem;
            }
        }
        printf("The GCD of %d and %d is %d.\n", num1, orinum2, gcd);
*/      i++;
    }

    fclose(input);

}

我检查过的每个网页和资源都表明这应该可以工作,但由于某种原因它不是。

【问题讨论】:

    标签: scanf formatted-input


    【解决方案1】:

    fscanf 将“返回成功匹配和分配的输入项的数量”:

    #include <stdio.h>
    
    int main()
    {
        FILE *input = fopen("input.txt", "r"); ;
        int num1, num2;
    
        while(fscanf(input, "%d %d", &num1, &num2) > 0)
            printf("%d\t%d\n", num1, num2);
    
        fclose(input);
    }
    

    模式 ("%d %d") 将匹配并分配两个整数,由任意数量的 whitespace characters 分隔。

    空白字符包括制表符 (\t) 和换行符 (\n)。

    【讨论】:

    • 你能澄清你的第三点吗?至于第 2 点,输入实际上没有字符“/”和“t”,我更改了原始帖子中的格式以准确描述文本文件。如果不是在代码段中完成,stackoverflow 似乎会弄乱我的格式。
    • 那么您将如何更改格式以便它读取信息直到遇到新行? [^\n] 似乎是互联网上大多数人推荐的方式。
    • 第三点是关于正则表达式 (en.wikipedia.org/wiki/Regular_expression)。 [^\n] 表示正则表达式中的(除换行符之外的任何内容)。 fscanf 模式不是正则表达式,所以你不能在那里使用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-13
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多