从C中的文件读取一行并提取输入数 [英] Read a line from file in C and extract the number of input

查看:116
本文介绍了从C中的文件读取一行并提取输入数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件 input.dat .在此文件中,共有3行:

I have a file input.dat. In this file, there are 3 lines:

1 2 3
5 7 10 12
8 9 14 13 15 17

我将使用C读取三行之一,并返回元素的数量. 例如,我想将第二行5 7 10 12读入内存,并还返回第二行中的值数,即4.我的代码在下面...

I am going to read one of the three lines using C, and return the number of the elements. For example, I want to read the 2nd line 5 7 10 12 into memory, and also return the number of values in the 2nd line, which is 4. My code is below...

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

#define STRING_SIZE 2000

int main() {
    FILE *fp = fopen("in.dat", "r");
    char line[STRING_SIZE];
    int lcount = 0, nline = 1, sum = 0, number;

    if (fp != NULL) {
        while (fgets(line, STRING_SIZE, fp) != NULL) {
            if (lcount == nline) {
                while (sscanf(line, "%d ", &number)) {
                    sum++;
                }
                break;
            } else {
                lcount++;
            }
        }
        fclose(fp);
    }
    exit(0);
}

当我运行这段代码时,它永远不会像死循环一样停止.这是什么问题?

When I run this code, it never stops like a dead loop. What is the problem here?

推荐答案

循环while (sscanf(line, "%d ", &number))继续解析该行中的第一个数字.

the loop while (sscanf(line, "%d ", &number)) keeps parsing the first number in the line.

您应该改用strtol:

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

#define STRING_SIZE 2000

int main() {
    FILE *fp = fopen("in.dat", "r");
    char line[STRING_SIZE];
    int lcount = 0, nline = 1;

    if (fp != NULL) {
        while (fgets(line, STRING_SIZE, fp) != NULL) {
            if (lcount == nline) {
                char *p = line, *q;
                int count = 0;
                for (;;) {
                    long val = strtol(p, &q, 0);    // parse an integer
                    if (q == p) {
                        // end of string or not a number
                        break;
                    }
                    // value was read into val. You can use it for whatever purpose
                    count++;
                    p = q;
                }
                printf("%d\n", count);
                break;
            } else {
                lcount++;
            }
        }
        fclose(fp);
    }
    return 0;
}

这篇关于从C中的文件读取一行并提取输入数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆