【问题标题】:Reading multiple lines in C using fscanf使用 fscanf 在 C 中读取多行
【发布时间】:2018-04-07 16:35:55
【问题描述】:

我目前正在做一个 uni 项目,该项目必须读取以 .txt 格式给出的多行输入序列。这是我第一次使用 C 语言,所以我不太了解使用 fscanf 读取文件然后处理它们。我写的代码是这样的:

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

int main() {
    char tipo [1];
    float n1, n2, n3, n4;
    int i;
    FILE *stream;
    stream=fopen("init.txt", "r");
    if ((stream=fopen("init.txt", "r"))==NULL) {
        printf("Error");
    } else {
        i=0;
        while (i<4) {
            i++;
//i know i could use a for instead of a while
            fscanf(stream, "%s %f %f %f %f%", &tipo, &n1, &n2, &n3, &n4);
            printf("%s %f %f %f %f", tipo, n1, n2, n3, n4);
        }
    }
    return 0;
}

我的“init”文件格式如下:

L 150.50 165.18 182.16 200.50
G 768.12 876.27 976.56 958.12
A 1250.15 1252.55 1260.60 1265.15
L 200.50 245.30 260.10 275.00
A 1450.15 1523.54 1245.17 1278.23
G 958.12 1000.65 1040.78 1068.12

我不知道如何告诉程序在读取第一行后跳过一行。

提前感谢您的帮助!

【问题讨论】:

  • 将&amp;tipo 的值作为第一个参数传递在两个方面是不好的:你传递一个指向 1 个字符的数组的指针,但 %s 期望一个指向 char 的指针指向第一个字符缓冲区有足够的空间来读取非空白字符的字符串。 C 中的字符串以空值结尾,因此在您的情况下写入 2 个字符,但您的数组有 1 个空间。
  • 我假设您的代码不起作用。解释如何。
  • 一般情况下,避免使用scanf 或fscanf。众所周知,它们很难使用。使用fgets 一次读取每一行,然后您可以在每个结果字符串上使用sscanf。
  • 如果我错了,请纠正我。这是你想要的输出吗?L 150.50 165.18 182.16 200.50 A 1250.15 1252.55 1260.60 1265.15 A 1450.15 1523.54 1245.17 1278.23
  • 我认为fscanf 出了名的难用。这很容易。 Don't use it.

标签: c scanf


【解决方案1】:

使用fscanf(stream, "%*[^\n]\n") 跳过行。只需添加一个if 语句来检查要跳过的行号。 if (i == 2) 跳过第二行。 还将char tipo[1] 更改为char tipo 并将printf 和fscanf 中的“%s”更改为“%c”

while (i++ < 4) 
{
    if (i == 2) // checks line number. Skip 2-nd line
    {
        fscanf(stream, "%*[^\n]\n");
    }
    fscanf(stream, "%c %f %f %f %f\n", &tipo, &n1, &n2, &n3, &n4);
    printf("%c %f %f %f %f\n", tipo, n1, n2, n3, n4);
}

您还打开文件两次。 if(streem = fopen("init.txt", "r") == NULL) 为真,因为您已经打开了文件。

【讨论】:

  • 非常感谢您的帮助,尤其是 fopen == null 的帮助。由于我是新手,所以我不知道
  • 只需删除 stream=fopen(“init.txt”,”r”) 因为您打开文件两次。你不需要它。
【解决方案2】:

响应“我不知道如何告诉程序在读取第一行后跳过一行。”就这样做吧!

while (i<4) 
{
    i++;
    //i know i could use a for instead of a while
    fscanf(stream, "%s %f %f %f %f%", &tipo, &n1, &n2, &n3, &n4);
    if(i != 2) //skipping second line
        printf("%s %f %f %f %f", tipo, n1, n2, n3, n4);

}

此外,使用 1 元素数组也没有任何意义。如果您只想使用char 元素,请将其从char tipo [1]; 更改为char tipo;,并将您各自的"%s" 更改为"%c"。但是,如果您希望它是 string 元素:将其从 char tipo [1]; 更改为 char *tipo; 或 char tipo [n]; 并保留您的 "%s"。

【讨论】:

  • 是的,我不需要字符串,所以这对我有帮助!
【解决方案3】:

当您只打算读取一个字符时,没有理由使用 char 数组(字符串)。

这样做:

char tipo;

和

fscanf(stream, "%c %f %f %f %f%", &tipo, &n1, &n2, &n3, &n4);

你的代码应该可以工作。注意 c 而不是 s。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多