简体   繁体   English

使用strcpy更新结构中的char []字段。 C中的指针问题

[英]Updating char[] field in a struct with strcpy. Pointer issue in C

I am wondering how i can set a struct's string value with a tokenized line from a file. 我想知道如何从文件中用标记化的行设置结构的字符串值。 basically i am reading in a line like "Person 100 100" (delimited by \\t ) and i need to set the string value of a struct with what's returned. 基本上,我正在阅读"Person 100 100" (由\\t分隔)这样的行,并且我需要使用返回的值来设置结构的字符串值。

Error message: 错误信息:

||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 ===|

Code snippet: 程式码片段:

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 function is define as follows: strcpy函数的定义如下:

char *strcpy(char *restrict s1, const char *restrict s2);

do not know the student structure, so you may pass parameters error in the first parameters. 不知道学生的结构,因此您可能会在第一个参数中传递参数错误。 and below code is ok: 和下面的代码是可以的:

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM