0

我想知道如何使用文件中的标记化行设置结构的字符串值。基本上我正在读一行"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);
}
4

1 回答 1

1

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;
}
于 2012-05-17T03:24:21.270 回答