我想知道如何使用文件中的标记化行设置struct的字符串值。基本上我正在阅读像"Person 100 100"
这样的行(由\t
分隔),我需要设置一个结构的字符串值和返回的内容。
错误讯息:
||In function 'main':|
|32|warning: passing argument 1 of 'strcpy' from incompatible pointer type|
c:\program files (x86)\codeblocks\mingw\bin\..\lib\gcc\mingw32\4.4.1\..\..\..\..\include\string.h|45|note: expected 'char *' but argument is of type 'char **'|
||=== Build finished: 0 errors, 1 warnings ===|
代码段:
char buffer[20];
fgets(buffer, 20, file);
while (*buffer != EOF)
{
struct student temp;
char *result = NULL;
//set name
strcpy(temp.name,strtok(buffer,"\t"));
//set midterm
result = strtok(NULL, "\t");
temp.midterm = atoi(result);
//set final
result = strtok(NULL, "\t");
temp.final = atoi(result);
}
答案 0 :(得分:1)
strcpy函数定义如下:
char *strcpy(char *restrict s1, const char *restrict s2);
不知道学生结构,所以你可能会在第一个参数中传递参数错误。以下代码没问题:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student
{
char name[128];
int midterm;
int final;
};
char buffer[] = {"Person 100 100"};
//fgets(buffer, 20, file);
int main()
{
//while (*buffer != EOF)
{
struct student temp;
char *result = NULL;
//set name
strcpy(temp.name,strtok(buffer,"\t"));
//set midterm
result = strtok(NULL, "\t");
temp.midterm = atoi(result);
//set final
result = strtok(NULL, "\t");
temp.final = atoi(result);
printf("name = %s, midterm = %d, final = %d\n", temp.name, temp.midterm, temp.final);
}
return 0;
}