【问题标题】:fscanf() only reads last integer per linefscanf() 只读取每行的最后一个整数
【发布时间】:2015-11-19 04:22:12
【问题描述】:

我正在尝试使用fscanf 读取文件并将其内容存储在数组中。每行包含四个整数值,需要放置在四个不同的数组中。我的代码读取每一行,但将每一行的最终整数值存储在所有四个数组中。

我尝试过使用fgets(),这似乎会导致更多问题。更改 fscanf() 调用中的格式也无济于事。

为什么会跳过每行的前三个值?

代码:

FILE *file;
int process_count, p_id[process_count], io_burst[process_count], priority[process_count], cpu_burst[process_count];

file = fopen(argv[1], "r");
if (!file) { error("File open failed"); }

process_count = atoi(argv[2]);

for (int i = 0; i < process_count; i++)
{
    if (fscanf(file, "%i %i %i %i", &p_id[i], &cpu_burst[i], &io_burst[i], &priority[i]) < 4)
    {
        error("File read failed");
    }

    printf("p_id: %i\n", p_id[i]);
    printf("cpu_burst: %i\n", cpu_burst[i]);
    printf("io_burst: %i\n", io_burst[i]);
    printf("priority: %i\n\n", priority[i]);
}

fclose(file);

输入:

0           10           4           2
1            8           2           1
2           12           0           5
3            2           4           4
4            8           3           0
5            6           4           2
6            4           0           5
7           16           7           5
8           14           0           1
9            2          10           1

输出:

p_id: 2
cpu_burst: 2
io_burst: 2
priority: 2

p_id: 1
cpu_burst: 1
io_burst: 1
priority: 1

p_id: 5
cpu_burst: 5
io_burst: 5
priority: 5

p_id: 4
cpu_burst: 4
io_burst: 4
priority: 4

p_id: 0
cpu_burst: 0
io_burst: 0
priority: 0

p_id: 2
cpu_burst: 2
io_burst: 2
priority: 2

p_id: 5
cpu_burst: 5
io_burst: 5
priority: 5

p_id: 5
cpu_burst: 5
io_burst: 5
priority: 5

p_id: 1
cpu_burst: 1
io_burst: 1
priority: 1

p_id: 1
cpu_burst: 1
io_burst: 1
priority: 1

【问题讨论】:

  • 如果先将数组清零会怎样?
  • 你需要设置process_count的值你使用它来指定数组的大小。您的数组很可能都是零长度(尽管这不可靠,因为此时 process_count 未初始化)。

标签: c arrays scanf


【解决方案1】:

这是一个错误:

int process_count, p_id[process_count],

process_count 是一个未初始化的变量,因此它不能用于数组维度(或其他任何东西)。

要解决此问题,您可以将代码更改为:

int process_count = atoi(argv[2]);

if ( process_count < 1 )
    exit(EXIT_FAILURE);    // or similar

int p_id[process_count], io_burst[process_count], priority[process_count], cpu_burst[process_count];

【讨论】:

  • 哇,成功了。我不敢相信我花了多长时间试图解决这个问题。谢谢。
【解决方案2】:

您的程序中有未定义的行为。

int process_count, p_id[process_count], io_burst[process_count], cpu_burst[process_count];
...
process_count = atoi(argv[2]);

该代码在初始化之前使用process_count

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-21
    • 2014-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多