问题描述
我想我应该改一下我的问题。我的结构如下:
struct profile {
char name[30];
int age,phoneNo;
};
James brown,35y,0123456789
Mary brown,45y,0123987456
目前,我已经编写了一个使用该人的姓名/年龄/电话号码来搜索记录的代码,我想将记录存储到我拥有的结构中。我正在尝试使用strtok
将数据与逗号分开,但是我的代码无法正常工作。
int main()
{
char search[50];
char record[50];
const char s[2] = ",";
char* token;
struct profile c;
FILE* fPtr;
if (fPtr = fopen("profile.txt","r"))
{
// flag to check whether record found or not
int foundRecord = 0;
printf("Enter name to search : ");
// fgets gets name to search
fgets(search,50,stdin);
//remove the '\n' at the end of string
search[strcspn(search,"\n")] = 0;
while (fgets(record,fPtr))
{
// strstr returns start address of substring in case if present
if (strstr(record,search))
{
token = strtok(record,s);
while (strtok != NULL)
{
scanf("%s",c.name);
token = strtok(record,s);
scanf("%d",c.age);
token = strtok(record,c.phoneNo);
token = strtok(NULL,s);
printf("Your details: ");
printf("%s,%d,%d\n",c.name,c.age,c.phoneNo);
}
foundRecord = 1;
}
}
if (!foundRecord)
printf("%s cannot be found\n",search);
fclose(fPtr);
}
else
{
printf("File cannot be opened\n");
}
}
我以前从未使用过strtok
,而且不确定如何将每个令牌存储到每个结构变量中。有人可以向我解释如何在代码中修复strtok
函数吗?
解决方法
根据评论中的建议,您可以使用strtok
轻松读取逗号分隔的字符串。您可以使用atoi
/ sscanf
从年龄中提取整数值。我对您的代码做了一些修改,以便从文件读取以分配给struct数组:
// Array for storing Profiles
struct profile profiles[2];
FILE* fPtr;
if (fPtr = fopen("profile.txt","r")) {
int index = 0;
while (fgets(record,50,fPtr) != NULL) {
// Extract name
char *pStr = strtok(record,",");
if (pStr != NULL) {
strcpy(profiles[index].name,pStr);
}
// Extract Age
pStr = strtok(NULL,");
if (pStr != NULL) {
profiles[index].age = atoi(pStr);
}
// Extract Phone No
pStr = strtok(NULL,");
if (pStr != NULL) {
profiles[index].phoneNo = atoi(pStr);
}
index++;
}
for (int i = 0; i < 2; i++) {
printf("%s %d %d\n",profiles[i].name,profiles[i].age,profiles[i].phoneNo);
}
fclose(fPtr);
}
运行此命令时,我可以看到预期的输出:
src : $ cat profile.txt
James Brown,35y,0123456789
Mary Brown,45y,0123987456
src : $ gcc readfiletostructarr.c
src : $ ./a.out
James Brown 35 123456789
Mary Brown 45 123987456