下面的程序应该读取txt
文件并将数据放入结构中。但它给出了一个指针错误。它在strcpy()
中给出了关于指针的错误。我是C.的新人。什么错了?
#include <stdio.h>
#include <string.h>
int main()
{
struct citydata {
char city[20];
int temp;
};
struct citydata values[15];
struct citydata Avg;
struct citydata high;
struct citydata low;
FILE* inp;
int reccount = 0;
int x = 0;
char s;
int n;
inp = fopen("mydata.txt", "r");
if (!inp) {
printf("Unable ot open file\n");
}
while (fscanf(inp, "%s %d", s, &n) != EOF) {
strcpy(values[x].city, s);
values[x].temp = n;
x++;
}
fclose(inp);
}
如果您编译此代码(例如,使用gcc),则会收到以下警告:
test.c:27:24: warning: format ‘%s’ expects argument of type ‘char *’, but argument 3 has type ‘int’ [-Wformat=]
while (fscanf(inp, "%s %d", s, &n) != EOF) {
^
test.c:28:32: warning: passing argument 2 of ‘strcpy’ makes pointer from integer without a cast [-Wint-conversion]
strcpy(values[x].city, s);
^
In file included from test.c:2:0:
/usr/include/string.h:125:14: note: expected ‘const char * restrict’ but argument is of type ‘char’
extern char *strcpy (char *__restrict __dest, const char *__restrict __src)
所以,正如评论所暗示的那样,你不能直接扫描到结构中;您只能扫描C标准库识别的更简单类型:整数,浮点数,char *
字符串等。同样,您不能从结构中执行字符串复制,而不是字符串。
C是一种强类型语言,很少允许隐式转换。在某些情况下,您可以传递整数而不是浮点数,反之亦然,但没有“神奇地转换”为字符串,或者从字符串中“神奇地解析”。
fopen()
失败,你不能继续运行其余的代码。您应该exit(EXIT_FAILURE);
或在main()
块内的else()
中包装其余代码。printf("error message here")
它应该fprintf(stderr,"error message here")
。此外,标准C库会将您可以获得的错误代码作为errno
变量,或者您可以使用perror()
函数将错误消息打印到标准错误流。还有一些其他相关的相关功能(如strerror()
,`err()等),我不会在这里介绍。使用指针犯一些错误=)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct citydata
{
char *city;
int temp;
} citydata;
int main()
{
char *s;
citydata *values;
values = (citydata*)malloc(sizeof(citydata) * 16);
FILE * inp;
int reccount = 0;
int x = 0;
int n;
inp = fopen("mydata.txt", "r");
if(!inp)
printf("Unable ot open file\n");
while (fscanf(inp,"%s %d",s, &n) != EOF)
{
values[x].city = (char*)malloc(sizeof(char) * 20);
strcpy(values[x].city, s);
values[x].temp = n;
x++;
}
fclose(inp);
}