strstr 函数误打误打

strstr function misundersandings

本文关键字:函数 strstr      更新时间:2023-10-16

strstr 函数有问题。我试图编译密码程序,但它掉了下来。任何帮助将不胜感激

#include <stdio.h>
#include <string.h>
using namespace std;
int main(){
    char s[5], password[]="kuku";
    int i,k=0;
    for (i=0; !k && i<3;i++){
        printf(" enter password: n");
        gets(s);
        if (strstr(s.password[])) k=1;
    }
    if(k) printf("password accepted");
    else printf("password not accepted");
    return 0;
}

if (strstr(s.password[](( k=1;

strstr(( 需要两个参数(haystack 和 needle,意思是你想在大海捞针中找到针(。你只传递一个参数,这是错误的。

正确的代码将是这样的:

if (strstr(s, password) != NULL) k=1;

在此表达式中

strstr(s.password[])

有两个错误。第一个是使用点时参数的分隔符是逗号。

第二个是,您必须使用表达式password而不是构造password[]

考虑到函数strstr不适合检查两个字符串是否相等。最好使用函数strcmp

并且功能gets不受C标准支持。请改用函数fgets

当您尝试将程序编译为C++程序时,请使用标准类std::string而不是原始字符数组。