【问题标题】:search 2 different words in one line of a txt file in C program在C程序中的txt文件的一行中搜索2个不同的单词
【发布时间】:2017-02-28 17:33:35
【问题描述】:

我是 C 新手,我收到了一个 .txt 文件,其中包含如下数据:

  1. ID 日期时间名称国家
  2. 43 12/2 01:18 艾米 AB
  3. 347 12/12 12:30 艾米 BC
  4. 95 10/1 10:00 鲍勃 AB
  5. ...

姓名将仅与 Amy/Bob/Cathy 相同,并且

国家/地区将仅等于 AB/BC/BD/DE

我需要读取文件并做以下事情:

示例 1,我需要在 .txt 文件中搜索 country = AB 的 Amy,并计算有多少数据满足这种情况

示例 2,使用 country = 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" 进行比较,但我该怎么办? 请帮忙,谢谢!

【问题讨论】:

  • C 不是 C++。不要垃圾标签
  • 可以分享一下.txt文件的sn-p吗?
  • strcmp(s, ... 不能是 == 0 同时带有“Amy”和“AB”
  • 您可以将带有子字符串"Amy AB"strstr 应用于使用fgets 读取的整行。

标签: c string search


【解决方案1】:

假设您的行始终采用以下格式:

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);

其中namecountry 是两个缓冲区,有足够的空间来存储数据。


例子:

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);

on wandbox


另一种可能的解决方案是使用strstr 来定位输入中特定子字符串(在您的情况下为名称和国家/地区) 的位置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多