gpt4 book ai didi

c++ - 在 C++ 中转换参数时出错

转载 作者:行者123 更新时间:2023-11-30 00:59:01 25 4
gpt4 key购买 nike

头文件

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

当我尝试编译时,我得到这个错误:

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

我正在尝试将数组的第一个元素作为 int 读取,以便我可以使用 atoi 函数对其进行比较。我有一个参数不匹配,但我找不到它在哪里。知道出了什么问题吗?

最佳答案

atoi 需要一个字符串作为输入参数,但是 num[0] 是一个 char。因此错误。您可以简单地使用 int n = num[0] - '0' 来获取整数值(假设 num 仅包含所有数字)。

关于c++ - 在 C++ 中转换参数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5088688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com