c/c++语言开发共享strstr仅在我的子字符串位于字符串末尾时才起作用

我现在写的这个程序遇到了一些问题。

这是我的主要内容:

int main() { char haystack[250], needle[20]; int currentCharacter, i=0; fgets(needle,sizeof(needle),stdin); //getting my substring here (needle) while((currentCharacter=getchar())!=EOF) //getting my string here (haystack) { haystack[i]=currentCharacter; i++; } wordInString(haystack,needle); return(0); } 

和我的function:

 int wordInString(const char *str, const char * wd) { char *ret; ret = strstr(str,wd); printf("The substring is: %sn", ret); return 0; } 

    你用fgets()读取一个字符串,用getchar()读取另一个字符串到文件末尾。 在两个字符串的末尾都有一个尾随'n' ,因此strstr()只能匹配子字符串,如果它位于主字符串的末尾。 此外,您不会在haystack的末尾存储最终的'' 。 您必须这样做,因为haystack是一个本地数组(自动存储),因此不会隐式初始化。

    您可以通过这种方式纠正问题:

    需要了解更多c/c++开发分享strstr仅在我的子字符串位于字符串末尾时才起作用,也可以关注C/ C++技术分享栏目—计算机技术网(www.ctvol.com)!

     //getting my substring here (needle) if (!fgets(needle, sizeof(needle), stdin)) { // unexpected EOF, exit exit(1); } needle[strcspn(needle, "n")] = ''; //getting my string here (haystack) if (!fgets(haystack, sizeof(haystack), stdin)) { // unexpected EOF, exit exit(1); } haystack[strcspn(haystack, "n")] = ''; 

      以上就是c/c++开发分享strstr仅在我的子字符串位于字符串末尾时才起作用相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/980644.html

      (0)
      上一篇 2021年12月14日
      下一篇 2021年12月14日

      精彩推荐