我想知道如何使用文件中的标记行设置结构的字符串值。基本上我正在阅读像 "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);
}
最佳答案
strcpy函数定义如下:
char *strcpy(char *restrict s1, const char *restrict s2);
不知道student结构,所以第一个参数可能传递参数错误。下面的代码就可以了:
#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;
}
关于c - 使用 strcpy 更新结构中的 char[] 字段。 C中的指针问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10627968/