2015-07-03 488 views
-3

我在编译此源时遇到问题。 这是我的源:如何解决“从'char *'到'char'错误的无效转换?

#include <iostream> 
#include <string> 

using namespace std; 
char pass[7],d; 
int v; 

int isvalid(char pass); 

int main(int argc, char** argv) { 
    cout<<"Enter Password :"; 
    gets(pass); 
    cout<<endl; 
    v=isvalid (pass); 
    if(v==1){ 
     cout<<"The Password is Correct . You can Come in"<<endl; 
    } 
    else{ 
     cout<<"The Password in InCorrect ! You Can't Come In"<<endl; 
    } 
    system("PAUSE"); 
    return 0; 
} 
/*-----------Functions--------------*/ 
int isvalid(char pass){ 
    d="Pokerface"; 
    if(pass==d){ 
     return 1; 
    } 
    else{ 
     return 0; 
    } 
} 

应该从用户那里得到一个密码,并参考isValid功能检查,并说这是正确的或没有,但编译器(DEV C++ 5)显示我这些错误:

In function 'int main(int, char**)': 
14 17  [Error] invalid conversion from 'char*' to 'char' [-fpermissive] 
8 5  [Note] initializing argument 1 of 'int isvalid(char)' 
    In function 'int isvalid(char)': 
26 3 [Error] invalid conversion from 'const char*' to 'char' [-fpermissive] 
28  recipe for target 'main.o' failed 

问题是什么?请帮帮我。

+0

变量'pass'的类型是'字符*''不char'。它们之间有区别。 'char *'是指向char的指针。将函数'isvalid'的参数类型更改为'char *'而不是'char',然后修改方法。 –

+0

char是1个字节,char *是一个4字节的指针,指向字节数组中的第一个字符。 –

回答

1

pass是一个char数组(char *),而你的isvalid函数取char作为第一个参数。我怀疑你想改变你的isvalid功能,因此,它需要一个char*作为参数,就像这样:

int isvalid(char* pass){

另外,请记住,当你这样做:

if (pass==d)

你不是比较字符串,而是指针。如果你想检查两个字符串是否相同,那么这是行不通的

对于字符串比较使用strcmp(str1, str2)string.h

0
int isvalid(char pass) 

你可能意味着需要在char*那里,但你不应该做,要么:使用std::string代替。此外,您的功能应返回bool而不是int

bool isvalid(const std::string& pass) 

然后,您应该更新passdstd::string S以及和使用std::cin代替getsstdin阅读。 passd没有理由成为全局变量,因此使它们成为本地函数。

如果你保持你的功能为char*你的比较不会奏效,因为你只是比较指针。你需要strncmp

2

既然你已经标记了C++对这个问题,我会建议使用std::string

#include <iostream> 
#include <string> 
using namespace std; 

bool isvalid(const std::string & pass); 

int main(int argc, char ** argv) { 
    string pass; 
    cout << "Enter Password" << endl; 
    cin >> pass; 
    if (isvalid(pass)) 
     cout << "The Password is Correct. You can Come in" << endl; 
    else 
     cout << "The Password in InCorrect ! You Can't Come In" << endl; 
    return 0; 
} 

bool isvalid(const std::string & pass) { 
    return pass == "Pokerface"; 
} 
+0

@MattMcNabb肯定,修正 – Shreevardhan

相关问题