c - strstr() 不适用于 C

标签 c linux coredump strstr

我有下面的代码。问题是当我运行它时,它没有显示我提示的搜索;在 for 中尝试 printf("%s", strstr(tracks[i], search_for)) 返回 null,但是对 tracks 做同样的事情没有问题[i]search_for。请帮忙!

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

char tracks[][80]={
  "I left my heart in Harvard Med Scholl",
  "Newark, Newark - a wonderful town",
  "Dancing with a Dork",
  "From here to maternity",
  "The girl from Iwo Jima",
};

void find_track(char search_for[]){
  int i;
  for(i=0; i<5; i++){
    if(strstr(tracks[i], search_for)){
      printf("Track %i: '%s'\n", i, tracks[i]);
    }
  }
};

int main(){

  char search_for[80];
  printf("Search for: ");
  fgets(search_for, 80, stdin);
  find_track(search_for);
  return 0;
}

最佳答案

正如我们在 fgets() 中看到的那样文档,如果行末有换行符,它将包含在生成的字符串中:

Reads at most count - 1 characters from the given file stream and stores them in str. The produced character string is always NULL-terminated. Parsing stops if end-of-file occurs or a newline character is found, in which case str will contain that newline character.

所以在这种情况下,如果我们输入 "Newark",那么我们有:

search_for[] = {'N', 'e', 'w', 'a', 'r', 'k', '\n', '\0', ...};

您需要删除多余的换行符。

关于c - strstr() 不适用于 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26287060/

相关文章:

c - 如何找到我用C语言编写的程序所需的最低系统要求?

c - 如何检查两个大小相等的数组在 C 中是否具有相同的值? (复杂度 O(n) )

linux - 不允许 Amazon EC2 Apache 符号链接(symbolic link)

linux - 是否可以计算 Linux 中每个接口(interface)发送/接收的 ICMP 数据包的数量?

c - 动态分配结构数组

c - 尝试将 char[] 存储到 char* 时出现问题

c - linux下C多线程程序如何有效锁定普通变量

c++ - C 中的另一个 coredump 问题

debugging - 为什么核心文件大于虚拟内存?

c++ - 崩溃为 __cxxabiv1::__cxa_pure_virtual () - vtable ptr 到抽象基类?