strstr函数误解

时间:2019-07-17 14:33:50

标签: c++ strstr

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

2 个答案:

答案 0 :(得分:0)

  

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

您想完成什么? strstr()需要两个参数(干草堆和needle,这意味着您要在干草堆中找到needle)。您只能传递一个参数,这是错误的。

正确的代码如下:

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

答案 1 :(得分:0)

在此表达式中

strstr(s.password[])

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

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

来代替结构password

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

C标准不支持函数gets。改用功能fgets

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