【问题标题】:C++ Argument of type "char" is incompatible with parameter of type "const char"“char”类型的 C++ 参数与“const char”类型的参数不兼容
【发布时间】:2020-01-20 15:36:14
【问题描述】:

我的导师让我使用 cstring 制作一个程序来检查程序是否为回文。 为什么它给我““char”类型的参数与“const char”类型的参数不兼容错误。

#include <iostream>
#include <cstring>
#include <string>
#include <sstream>

using namespace std;

int main()
{
    string str = "";
    int strcmpVal;
    int length = str.length();
    cout << "******************************" << endl;
    cout << "PALINDROME" << endl;
    cout << "******************************" << endl;
    cout << "Enter a word: ";
    getline(cin, str);
    char* cStr = new char[str.length() + 1];
    strcpy(cStr, str.c_str());
    for (int i = 0; i < (length / 2); i++)
    {
        strcmpVal = strcmp(cStr[i],cStr[(length -1) -1]);
    }

}

【问题讨论】:

  • 你能显示确切的错误信息,特别是它指的是哪一行?
  • """char" 类型的参数与"const char" 类型的参数不兼容错误。" 当询问错误消息时,请始终复制粘贴它们,而不是试图解释它们。没有办法,错误是关于尝试转换为const char,而不是const char*char 与指向char 的指针不同:char*

标签: c++ string for-loop c-strings palindrome


【解决方案1】:

首先是这个声明

int length = str.length();

没有意义,因为对象str 还为空。您必须在输入字符串后计算长度。

标准 C 函数 strcmp 比较字符串而不是单个字符。也就是说,cStr[i] 表达式的类型是 char,而函数将有一个 char * 类型的参数,如果传递给函数,该参数将具有表达式 cStr

所以改用这个循环

size_t i = 0;
size_t length = str.length();
while ( i < length / 2 && cStr[i] == cStr[length - i - 1] ) i++;

if ( i == length / 2 ) std::cout << "The string is a palindrome.\n";

考虑到这些陈述

char* cStr = new char[str.length() + 1];
strcpy(cStr, str.c_str());

是多余的。

你可以写

const char *cStr = str.c_str();

否则你需要在分配的内存不再使用后释放它。

delete [] cStr;

【讨论】:

  • 但由于某种原因,Visual Studio 不允许我在字符串上使用 strcmp。
  • @Albert 不要使用。问题是什么?我向你展示了如何编写循环。
【解决方案2】:
strcmp(cStr[i], cStr[(length - 1) - 1]);

cStr[i]char,但strcmp 的参数必须是char*s(指向char 的指针)。

但是在这里使用strcmp无论如何都是错误的,你只是想比较char,所以你需要宁:

strcmpVal = cStr[i] == cStr[(length -1) -1]);

但还有更多问题。我把它当作练习。

【讨论】:

  • 但由于某种原因,Visual Studio 不允许我在字符串上使用 strcmp。
  • @Albert 这正是重点,cStr[i]char。无论如何,当您使用 C++ 编写代码时,您应该坚持使用std::string
猜你喜欢
  • 1970-01-01
  • 2019-12-16
  • 2016-05-19
  • 2014-07-03
  • 1970-01-01
  • 1970-01-01
  • 2021-08-06
  • 2020-11-19
  • 2021-01-07
相关资源
最近更新 更多