【发布时间】:2015-12-03 13:27:49
【问题描述】:
我目前正在尝试读取由空格分隔的文件。我已经能够让它逐行读取,但现在我需要用空格分隔它,以便我可以将它放入一个数组中。如何将它分成数组?
#include <stdio.h>
int main ( void )
{
int data_array[3];
int num1;
int num2;
int num3;
static const char data[] = "data.txt";
FILE *file = fopen ( data, "r" );
if ( file == NULL )
{
printf("An error occured reading the file. Check to make sure file is not locked.");
}
else
{
char line [ 1024 ]; // hopefully each line does not exceed 1024 chars
while ( fgets ( line, sizeof line, file ) != NULL ) // reads each line
{
// reads each number into an array
scanf("%d %d %d", num1, num2, num3);
data_array[0] = num1;
data_array[1] = num2;
data_array[2] = num3;
}
fclose ( file ); // closes file
}
return 0;
}
【问题讨论】:
-
对不起,我不明白你想做什么。是否要将 data_array 存储在另一个数组中?
-
我的文件有这样一行:
3 5 12我想将这些数字中的每一个读入数组 data_array。 -
我猜你忘记粘贴行了。
-
您忘记在传递给 scanf 的变量之前添加 &。比如:scanf("%d %d %d", &num1, &num2, &num3);
-
根据您想要执行的操作,您可以将
fgets调用替换为直接在file上运行的fscanf调用,或者如果您需要保留line同样,您可以使用sscanf从line中提取数字。