标头文件
#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文件
#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;
}
当我尝试编译时,我收到此错误:
错误C2664:'atoi':无法转换 参数1从'const char'到 'const char *'1&gt;转变 从整数类型到指针类型 需要reinterpret_cast,C风格 演员或功能式演员
我正在尝试将数组的第一个元素作为int读取,因此我可以使用atoi函数进行比较。我有一个参数不匹配但我找不到它的位置。知道什么是错的吗?
答案 0 :(得分:4)
atoi
需要字符串作为输入参数,但num[0]
是char
。因此错误。您只需使用int n = num[0] - '0'
来获取整数值(假设num仅包含所有数字)。
答案 1 :(得分:2)
atoi需要"a string"
而不是'c'
har:
if (atoi(num[0]) == 0) // <- here
你想测试第一个字符是否为'0'?
if (num[0] == '0') { /* ... */ }
您想将单个字符转换为数字0 - 9
吗?
int i = num[0] - '0'; // every i not beeing 0 - 9 is not a number.
您是否只想检查 num[0]
是否为数字?
#include <ctype.h>
if (isdigit(num[0])) { /* ... */ }
答案 2 :(得分:0)
如果您确定它是一个数字,您可以使用它将char转换为int:
char* str = "012345";
int i = str[0] - 48; // Numbers start at 48 in ASCII table
if ( i==0 )
{ ... }