Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
函数strtok()和C中的混合变量类型_C_Struct_File Io_Strtok - Fatal编程技术网

函数strtok()和C中的混合变量类型

函数strtok()和C中的混合变量类型,c,struct,file-io,strtok,C,Struct,File Io,Strtok,我试图从文件中读取数据并将数据插入结构数组,文件的格式如下: ... 0087|www.google.com|2017.08.07 12:13:36 0150|www.yahoo.com|2018.10.06 04:03:12 ... 当数据类型被“|分离时,我使用strtok()来分离数据,这对字符串类型timestamp和domain都很有效,但是我能够在结构中正确存储数据,对于数据类型customerid我只获取结构中的内存地址,我如何解决这个问题?谢谢 #include <std

我试图从文件中读取数据并将数据插入结构数组,文件的格式如下:

...
0087|www.google.com|2017.08.07 12:13:36
0150|www.yahoo.com|2018.10.06 04:03:12
...
当数据类型被“
|
分离时,我使用
strtok()
来分离数据,这对字符串类型
timestamp
domain
都很有效,但是我能够在结构中正确存储数据,对于数据类型
customerid
我只获取结构中的内存地址,我如何解决这个问题?谢谢

#include <stdio.h>
#include <string.h>

struct AccessRecord {       
    int customerID;         
    char domain[256];
    char timestamp[21]; 
    };

struct AccessRecord rc[1000];


int main()
{
    int i = 0; char line[300]; 
    const char s[2] = "|";

    FILE *fd;
    fd = fopen("./example_data.ipb","r");


    while (fgets(line, sizeof(line), fd)) {

        char *token;

        token = strtok(line, s);

        rc[i].customerID = token;
        token = strtok(NULL, s);

        strcpy (rc[i].domain , token);
        token = strtok(NULL, s);


        strcpy (rc[i].timestamp , token);
        token = strtok(NULL, s);

        i++;
    }
    fclose(fd);

    return 0;
}
#包括
#包括
结构访问记录{
国际客户ID;
字符域[256];
字符时间戳[21];
};
结构访问记录rc[1000];
int main()
{
int i=0;字符行[300];
常量字符s[2]=“|”;
文件*fd;
fd=fopen(“./示例_data.ipb”,“r”);
while(fgets(line,sizeof(line),fd)){
字符*令牌;
令牌=strtok(行,s);
rc[i].customerID=token;
令牌=strtok(空,s);
strcpy(rc[i].域,令牌);
令牌=strtok(空,s);
strcpy(rc[i].时间戳,令牌);
令牌=strtok(空,s);
i++;
}
fclose(fd);
返回0;
}

注意提取数据的两种不同方式:

token = strtok(line, s);
rc[i].customerID = token;       // assignment of char* (to int, so suspect)

token = strtok(NULL, s);
strcpy (rc[i].domain , token);  // string copying
这是尽管事实上,这两个都是字符串。虽然客户ID是数字数据,但它是作为字符串存储的,因此应将其视为字符串

换句话说,由于它在结构中是一个整数,因此可以在读取时对其进行转换,例如:

token = strtok(line, s);
rc[i].customerID = strtol(token, NULL, 10);

分配给
customerID
时,需要解析
token()
中的数字。使用
strtol()
。但是,请注意,以
0
开头的数字被解析为八进制。@Barmar,这很容易通过使用
strtol()的
base
参数来解决。