【发布时间】:2026-02-13 09:30:01
【问题描述】:
我正在尝试创建一个程序,在该程序中读取包含未知行的文件,然后按空格拆分数据,然后将其添加到结构中。我在读取数据并将其添加到结构时遇到问题。尝试使用 GCC 编译时出现一些错误。他们来了。
program1.c: In function ‘initialize’:
program1.c:54:3: warning: format ‘%d’ expects argument of type ‘int *’, but argument 5 has type ‘int’ [-Wformat=]
if(fscanf(fp, "%s %f %d %s\n", *data[counter].type, data[counter].literAmount, *data[counter].miles, *data[counter].color) !=4) {
^
program1.c:57:2: warning: format ‘%f’ expects argument of type ‘double’, but argument 3 has type ‘float *’ [-Wformat=]
printf("data stored is: %s %f %d %s\n", *data[counter].type, data[counter].literAmount, data[counter].miles, *data[counter].color);
^
program1.c:57:2: warning: format ‘%d’ expects argument of type ‘int’, but argument 4 has type ‘int *’ [-Wformat=]
这是程序的代码。
#include<stdlib.h>
#include<stdio.h>
typedef struct importedData {
char *type[20];
float *literAmount;
int *miles;
char *color[20];
}DATA;
int main() {
int userInput;
initialize();
//Do while loop to loop through menu until exit.
do {
//Print statements to put out the output options
printf("Choose the option you would like to preform \n");
printf("1.Sort data from the float value & print high to low \n2.Sort data by the float value & print low to high\n3.Sort data by the int value & print high to low\n4.Sort data by the int value & print low to high");
scanf("%d", &userInput); //Scanner to take in the keyboard input
} while (userInput != 5);
return 0;
}
int numberOfLines() {
FILE *fp = fopen("hw3.data", "r"); //Opens file name and in the read format
int c = 0; //Count the number of characters
int count = 0; //Number of lines
if(fp == NULL) { //If file was not able to be opened program will exit
printf("Unable to read file. Closing");
return 0;
}
while((c = fgetc(fp)) != EOF) { //Get the character and make sure it isnt the END OF FILE
if(c == '\n') { //If the charcter is set to \n (New Line) will add one to counter
count++;
}
}
fclose(fp);
return count;
}
int initialize() {
DATA *data = malloc(numberOfLines() * sizeof(*data));
FILE *fp = fopen("hw3.data", "r"); //Opens file name and in the read format
int counter = 0;
int totalIteragions = numberOfLines();
while(counter < totalIteragions) {
if(fscanf(fp, "%s %f %d %s\n", *data[counter].type, data[counter].literAmount, *data[counter].miles, *data[counter].color) !=4) {
return -1;
}
printf("data stored is: %s %f %d %s\n", *data[counter].type, data[counter].literAmount, data[counter].miles, *data[counter].color);
}
}
有人可以向我解释为什么会发生此错误以及如何修复它以及将来捕获此类错误吗?感谢您的所有帮助。
编辑:我不必在结构指针中创建变量吗?我假设因为我使用 malloc 制作了一个结构数组,所以内存位置已经被分配,所以当你输入数据时,它将把它存储到每个内存位置。对吗?
【问题讨论】:
-
看起来你只是在你的代码周围扔
*s 并希望它们能在某个地方工作 -
除了投掷的星星,(那些在许可的武术中心之外不是非法的吗?),整体设计 - 迭代文件两次,一次计算行数,然后再次打印内容,可疑。
-
使用 gcc -g a.c 中的 -g 标志编译您的代码,然后使用调试器 gdb 运行它...您的生活将大大改善。
-
同样从
DATA的定义中删除所有的星星 -
@MattMcNabb 第一条消息没有错——那是
scanf,而不是printf
标签: c arrays file struct storage