如何修复C++中‘char’转‘const char*’无效转换错误?
解决C风格字符串strcmp转换错误问题
错误根源
strcmp函数要求两个参数都是**const char*类型**(即C风格字符串的首地址),但你代码里传入的是单个char值,导致类型不匹配,触发转换错误。下面逐个解决你的三个错误:
1. 第一个错误:strcmp(person.name[i],person.surname[i]) != '\0'
问题:
person.name是char[30]类型的字符串,person.name[i]是该字符串的第i个单个字符,并非整个字符串的首地址;strcmp返回值是int(相等返回0,不等返回非0),你用'\0'(ASCII值为0的字符)和它比较,逻辑上应直接和整数0比较;- 从代码逻辑看,你应该定义了
contact类型的数组(比如contact person[30];),但循环里错误用person.name[i]访问第i个联系人的姓名,正确写法是person[i].name。
修正:
// 先定义通讯录数组 contact person[30]; int check = 0; // 提前定义check变量 for (int i = 0; i < 30; i++) { // 比较第i个联系人的name和surname字符串 if (strcmp(person[i].name, person[i].surname) != 0) // 输出整个字符串而非单个字符 cout << person[i].name << " " << person[i].surname << " " << person[i].phone_number << endl; check++; }
2. 第二、三个错误:strcmp(temp,person.name[i]) == 0 和 strcmp(temp1, person.surname[i]) == 0
问题:
temp和temp1被定义为char类型,只能存单个字符,但姓名是字符串,需要用char数组存储;- 同样,
person.name[i]是单个字符,应改为person[i].name访问第i个联系人的姓名字符串。
修正:
// 把单个char改为char数组,用于存储输入的姓名 char temp[30]; char temp1[30]; cout << "Insert the name of the contact to delete: \n"; cin >> temp; cout << "Insert the surname of the contact to delete: \n"; cin >> temp1; int check = 0; for (int i = 0; i < 30; i++) { // 比较输入字符串与第i个联系人的姓名、姓氏 if (strcmp(temp, person[i].name) == 0 && strcmp(temp1, person[i].surname) == 0) { cout << "Contact deleted!\n"; // 清空字符串,只需把第一个字符设为'\0' person[i].name[0] = '\0'; person[i].surname[0] = '\0'; person[i].phone_number[0] = '\0'; check++; } } // 将判断check的代码移到循环外,避免第一次循环没找到就直接返回 if (check == 0) { cout << "This person is not in your contact list\n "; }
修正后的完整代码
#include <iostream> #include <cstring> using namespace std; struct contact { char name[30]; char surname[30]; char phone_number[30]; }; int main() { // 定义通讯录数组,最多存30个联系人 contact person[30]; // 可在此添加初始化联系人的代码 int check = 0; for (int i = 0; i < 30; i++) { if (strcmp(person[i].name, person[i].surname) != 0) cout << person[i].name << " " << person[i].surname << " " << person[i].phone_number << endl; check++; } char temp[30]; char temp1[30]; cout << "Insert the name of the contact to delete: \n"; cin >> temp; cout << "Insert the surname of the contact to delete: \n"; cin >> temp1; check = 0; for (int i = 0; i < 30; i++) { if (strcmp(temp, person[i].name) == 0 && strcmp(temp1, person[i].surname) == 0) { cout << "Contact deleted!\n"; person[i].name[0] = '\0'; person[i].surname[0] = '\0'; person[i].phone_number[0] = '\0'; check++; } } if (check == 0) { cout << "This person is not in your contact list\n "; } return 0; }
内容的提问来源于stack exchange,提问作者Eternal23
相关产品推荐
相关产品推荐

