【问题标题】:Read numbers from text file and use them as input从文本文件中读取数字并将其用作输入
【发布时间】:2014-05-08 12:42:35
【问题描述】:

我有这段文字:

0 0 0 0 0 1
0 0 0 0 1 1
0 0 0 1 0 1
0 0 0 1 1 1

我想读取每行的前 5 个数字,然后将它们用作函数的输入。

我是 c 新手,只完成了这段代码,如果真的有什么作用的话。

    int v,o;
    FILE *mydata;

    if ((mydata = fopen("testinputs.txt", "rt"))==NULL)
    {
        printf ("file can't be opened'\n");
        exit(1);}


    fclose(mydata);

如何完成?

谢谢。

【问题讨论】:

  • 没有更简单的吗?我觉得有点难以理解。
  • @user3032539:有 3 个人试图回答您的问题(嗯,从技术上讲,他们为您完成了工作)。所有代码都包含解释代码功能的 cmets……如果您仍然不清楚这些答案中的某些内容,也许可以评论这些答案,要求澄清。如果任何答案解决了您的问题,请将该答案标记为已接受

标签: c text numbers


【解决方案1】:

好吧,假设您的文件名为“input.txt”,那么您需要做的就是:

#include <stdio.h>
#include <stdlib.h>

#define LINE_LEN 100
int main ( void )
{
    char line[LINE_LEN];
    int sum, i, read_cnt, numbers[5];//sum and i are there for my example usage
    FILE *in = fopen("input.txt", "r");//open file
    if (in == NULL)
    {
        fprintf(stderr, "File could not be opened\n");
        exit( EXIT_FAILURE);
    }
    while((fgets(line, LINE_LEN, in)) != NULL)
    {//read the line
        //scan 5 numbers, sscanf returns the number of values it managed to extract
        read_cnt = sscanf(
            line,
            "%d %d %d %d %d",
            &numbers[0],
            &numbers[1],
            &numbers[2],
            &numbers[3],
            &numbers[4]
        );
        //check to see if we got all 5 ints
        if (read_cnt != 5)
            printf("Warning: only read %d numbers\n", read_cnt);//whoops
        //just an example, let's add them all up
        for (sum= i=0;i<read_cnt;++i)
            sum += numbers[i];
        printf("Sum of numbers was: %d\n", sum);
    }
    return EXIT_SUCCESS;
}

使用这个 input.txt 文件:

1 2 3 4 5 
2 2 2 2 2
1 23 2 3 4
12 23

这给了我们以下输出:

Sum of numbers was: 15
Sum of numbers was: 10
Sum of numbers was: 33
Warning: only read 2 numbers
Sum of numbers was: 35

这应该更多足以让你开始

【讨论】:

  • +1 fgets()/sscanf() 并测试他们的结果。
【解决方案2】:

这是一个小代码,可以逐个字符读取并只存储想要的数字:

C 代码:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int c;                     // Character read from the file
    int cpt;                    // Counter (to get only 5 numbers per line)
    int i,j;                     // Array indexes
    int data[4][5];       // 2D integer array to store the data
    FILE *f;                // File

    if ((f = fopen("file.txt", "r")) == NULL)       // Open the file in "read" mode
    {
        printf ("file can't be opened'\n");
        exit(255);
    }

    // Counter and indexes initialization
    cpt=0;
    i=0;
    j=0;

    // Read the file till the EOF (end of file)
    while ((c = fgetc(f)) != EOF)
    {
        // If 5 numbers read, go to new line, first index in the data array and to the next line in the file
        if(cpt==5)
        {
            i++;
            cpt=0;
            j=0;
            while(c != '\n' && c != EOF)
                c=fgetc(f);
        }

        // If a number is read, store it at the right place in the array
        if(c>='0'&&c<='9')
        {
               // Convert character to integer (see ascii table)
            data[i][j] = c-'0';
            j++;
            cpt++;
        }
    }

        // Display the array
    for(i=0;i<4;i++)
    {
        for(j=0;j<5;j++)
            printf("%d ", data[i][j]);
        printf("\n");
    }

    fclose(f);
}

这是输出:

0 0 0 0 0
0 0 0 0 1
0 0 0 1 0
0 0 0 1 1

现在您可以使用二维数组,例如,如果您希望变量 a 具有第二行第三个数字,您可以:a = data[1][2] 不要忘记数组从索引 0 开始

希望这会有所帮助...

【讨论】:

  • 请不要发布第二个答案:复制此答案的内容,并将其添加到您的第一个帖子中...您的答案底部有一个小链接,上面写着 “编辑” :)
  • 我刚刚删除了上一个答案,因为它更多的是评论而不是答案,这将是我在页面上的唯一答案。谢谢你给我建议埃利亚斯! :)
  • 别提了,欢迎来到 SO,顺便说一句。我并不是说这个不好,但是为什么要按字符读取文件字符呢?当然,如果输入是完全不可预测的,你必须这样做,但是在这里,使用fgets + sscanf 使代码更容易阅读/理解/维护......更不用说:更短更干净,并且也可能更快......
  • 由于他是 C 新手,我认为最好发布一个代码来解释如何访问每个字符、EOF、ascii->int 转换等......并用 cmets 来解释.此外,如果文件的结构不太组织,则可以修改和重用此代码。但可以肯定的是,对于这个特定问题,这不是最好的方法,我的意思是它更具学术性
  • 好吧,如果你想更学术一点,这是一件好事,你可能需要将exit(-1) 更改为exit (EXIT_FAILURE) 或exit(255),因为退出代码是@987654321 @。当然,这不是 codereview.stackexchange,但我不认为第二个嵌套 while(c != '\n' and c != EOF) 循环也是一个不错的解决方案......我很抱歉成为一个如此迂腐的混蛋......我辛苦工作一天后总是这样:)
【解决方案3】:

也许对你有帮助:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
FILE *datafile;
int main()
{
    char line[100],*ch;
    int count;

    datafile = fopen ( "my.txt", "r");

    while ( fgets(line , sizeof line , datafile) != NULL )//fgets reads line by line
    {
        count = 0;
        ch = strtok ( line , " ");
        while ( count < 5 && ch != NULL )
        {


            printf("%d ",*ch - 48 );//*ch gives ascii value
            //pass to any function

            count++;
            ch = strtok ( NULL, " ");
        }

    }
    return 0;
}

上述程序通过整数传递整数。

【讨论】:

  • 这里不需要strtok,sscanf。手动转换数字字符串很好而且很花哨,但是你为什么要打扰呢?为什么不直接使用atoi?
  • 我应该使用 atoi(ch) 代替 *ch-48 吗?
  • 是的,因为 ATM,您假设输入中的所有整数都小于 10:*ch-48 仅将单个字符转换为数字,而 atoi(ch) 可以处理像“123”这样的输入,也。不过,IMO,sscanf 是完成这项工作的最佳工具
  • 谢谢,我在哪里可以得到更多这样的:P
猜你喜欢
  • 1970-01-01
  • 2022-11-30
  • 1970-01-01
  • 1970-01-01
  • 2013-12-30
  • 2015-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多