我是 C 新手,我得到了一个包含如下数据的 .txt 文件:
- ID 日期时间名称国家/地区
- 43 12/2 01:18 艾米·AB
- 347 12/12 12:30 艾米 BC
- 95 10/1 10:00 鲍勃·AB
- ...
名称仅等于 Amy/Bob/Cathy 并且
国家/地区仅等于 AB/BC/BD/DE
我需要读取该文件并执行以下操作:
示例1,我需要在.txt文件中搜索country = AB的Amy,并统计有多少条数据满足这种情况
示例 2,使用国家 = DE 和计数搜索 Amy
我不知道如何同时检查名称和国家/地区,这是我的代码:
#include <stdio.h>
#include <string.h>
int main(){
int i;
char s[10];
while(scanf("%s", s)==1){
if (strcmp(s,"Amy")==0){
if (strcmp(s,"AB")==0){
++i;
}
}
}
我认为第二个 if 不应该使用 s 与“AB”进行比较,但我能做什么? 请帮忙,谢谢!
最佳答案
假设您的行始终采用以下格式:
43 12/2 01:18 Amy AB
int int/int int:int string string
您可以使用scanf
来解析该行:
scanf("%*d %*d/%*d %*2d:%*2d %s %s", name, country);
其中name
和country
是两个有足够空间存储数据的缓冲区。
示例:
const char* s = "43 12/2 01:18 Amy AB";
char name[16]; char country[16];
sscanf(s, "%*d %*d/%*d %*2d:%*2d %s %s", name, country);
assert(strcmp(name, "Amy") == 0);
assert(strcmp(country, "AB") == 0);
<小时/>
另一种可能的解决方案可以使用 strstr
定位输入中特定子字符串(在您的情况下为名称和国家/地区)的位置。
关于c - 在C程序中在txt文件的一行中搜索2个不同的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42515274/