[英]How do I make a function in C that searches for line(s) that contains the selected characters in a file?
Sorry if the title is confusing.抱歉,如果标题令人困惑。 It might be better if I explain with the below code blocks.
如果我用下面的代码块来解释可能会更好。
Part of my code我的部分代码
typedef struct {
char name[50];
char num[9];
char email[50];
} Contacts;
Contacts Contact[50];
void search() {
char string[20];
printf("What are you searching for: ");
scanf("%19s", string);
file = fopen("StoredContacts.txt", "r");
while (!feof(file)) {
}
}
StoredContacts.txt StoredContacts.txt文件
Bobby,10,bobby@gmail.com
Abby,30,abby@gmail.com
Ada,20,ada@gmail.com
So basically my StoredContacts.txt contains names, ages and emails.所以基本上我的 StoredContacts.txt 包含姓名、年龄和电子邮件。 I separated the contacts with a comma and they can be correctly registered into Contact.
我用逗号分隔联系人,他们可以正确注册到联系人中。
What I want my search() to do is when I entered what I was looking for, the function would check each Contact and return me the full details of the person(s) I was looking for.我希望我的 search() 做的是当我输入我要查找的内容时,该函数将检查每个联系人并向我返回我要查找的人的完整详细信息。 For example, if I entered "A", I want it to print "Abby,30,abby@gmail.com" and "Ada,20,ada@gmail.com".
例如,如果我输入“A”,我希望它打印“Abby,30,abby@gmail.com”和“Ada,20,ada@gmail.com”。 If I entered "da", I want it to return "Ada,20,ada@gmail.com".
如果我输入“da”,我希望它返回“Ada,20,ada@gmail.com”。 I tried using bsearch and realised it couldn't print the details of the person(s).
我尝试使用 bsearch 并意识到它无法打印人员的详细信息。
I used strstr
and finally made the search
function.我用了
strstr
,终于做出了search
功能。
The function now at first tests if there are any results that contain the string, then it runs again and prints the details of the person that contains the string in their name or age, or email.该函数现在首先测试是否有包含该字符串的任何结果,然后它再次运行并打印姓名或年龄或电子邮件中包含该字符串的人的详细信息。
void search() {
int result_count = 0;
char string[20];
char *result1, *result2, *result3;
printf("What are you searching for: ");
scanf("%19s", string);
file = fopen("StoredContacts.txt", "r");
if (!feof(file)) {
for (int i = 0; i < stored; i++) {
result1 = strstr(Contact[i].name,string);
result2 = strstr(Contact[i].num,string);
result3 = strstr(Contact[i].email,string);
if (result1 || result2 || result3) {
result_count++;
}
}
}
if (result_count > 0) {
printf("There are %d results:\n", result_count);
if (!feof(file)) {
for (int i = 0; i < stored; i++) {
result1 = strstr(Contact[i].name,string);
result2 = strstr(Contact[i].num,string);
result3 = strstr(Contact[i].email,string);
if (result1 || result2 || result3) {
printf("%s,%s,%s\n", Contact[i].name, Contact[i].num, Contact[i].email);
}
}
}
}
else if (result_count <= 0) {
printf("None of the contacts contains %s", string);
}
fclose(file);
menu();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.