开发者

Error converting parameter in C++

Header file

#include <iostream>
#include <cstring>

const unsigned MaxLength = 11;

class Phone {
public:

    Phone(const char *phone) {
    setPhone(phone);
    }

    void        setPhone(const char Phone[ ]);
    const char* getPhone();

private:
    char phone[MaxLength+1];
};

Cpp file

#include "Phone.h"
#include <iostream>
#include <ctype.h>
#include <cstring>
#include <cstdlib> 

using namespace std; 
bool checkNum(const char* num);

void Phone::setPhone(const char Phone[ ]) {
    strncpy(phone, Phone, MaxLength);
    phone[MaxLength] = '\0';
}

const char* Phone::getPhone() {
    return phone;
}


int main() {
    Phone i1("12345678901");

    cout << i1.getPhone() << endl;
    if (checkNum(i1.getPhone())) 
        cout << "Correct" << endl;
    else 
        cout << "Invalid Wrong" << endl;

}

bool checkNum(const char* num) {
    bool flag = true;
        if (atoi(num[0]) == 0)
            flag = false;
    return flag;
}

When I tried to compile, I get this error:

error C2664: 'atoi' : cannot convert parameter 1 from 'const char' to 'const char *' 1> Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast

I am trying to read the first element of the array as an int so I can compare it using the atoi functi开发者_开发问答on. I am having a parameter mismatch but I can't find where it is. Any idea what's wrong?


atoi requires a string as an input parameter, however num[0] is an char. Hence the error. You can simply use int n = num[0] - '0' to get the integer value (assuming num contains all numbers only).


atoi takes "a string" and not a 'c'har:

 if (atoi(num[0]) == 0)  // <- here

Do you want to test if the first character is a '0'?

 if (num[0] == '0') { /* ... */ }

Do you want convert single chars to numbers 0 - 9?

 int i = num[0] - '0'; // every i not beeing 0 - 9 is not a number.

Do you want to just check if num[0] is a number?

 #include <ctype.h>

 if (isdigit(num[0])) { /* ... */ }


You can use this to convert a char to an int if you are sure its a number:

char* str = "012345";
int i = str[0] - 48; // Numbers start at 48 in ASCII table
if ( i==0 )
{ ... }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜