从"char"到"const char*"的无效转换[-fpermissive](idk why)

Invalid conversion from 'char' to 'const char*' [-fpermissive](idk why)

本文关键字:char -fpermissive why idk 无效 const 转换      更新时间:2023-10-16
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
    char s[101], pal[101];
    cin.getline(s,100);
    for (int i = strlen(s); i >= 0; i--)
        strcat(pal, s[i]);
    if (strcmp(s, pal) == 0)
        cout << "corect";
    else
        cout << "incorect";
    return 0;
}

你好。我试图验证一个单词是否是回文,它给了我错误:

"从'char'到'const char*'的转换无效[-fallowive]"。

这不是我第一次遇到这个烦人的错误,我需要一些帮助。有人可以解释我的代码出了什么问题,并(请:)(给我一些文章/理论/东西来理解为什么会发生此错误?谢谢你,很抱歉问这么愚蠢的问题。我看了1000遍,仍然不明白。

正如已经指出的那样,您收到错误的原因是因为您传递的是char而不是要strcat const char*

由于问题被标记为c++我将继续展示执行此操作的 c++ 方法。

#include <iostream>
#include <string>
int main() {
    std::string s, pal;
    std::getline(std::cin, s);
    for (auto it = s.rbegin(), end = s.rend(); it != end; ++it)
        pal.push_back(*it);
    if (s == pal)
        std::cout << "correct" << std::endl;
    else
        std::cout << "incorrect" << std::endl;
    return 0;
}

更喜欢 std::string 而不是使用原始的 c 样式字符数组,并且随之而来的是循环中使用reverse_iterator。

除了已经指出的strcat明显的错误之外,您不需要它,因为您可以直接填充数组pal。此外,当您向后迭代时,您应该从字符串的最后一个字符而不是 null 终止符开始,如下所示:

#include <iostream>
int main()
{
    char s[101], pal[101];
    if (std::cin.getline(s, 100))
    {
        int j = 0;
        for (int i = strlen(s) - 1; i >= 0; i--)
            pal[j++] = s[i];
        pal[j] = 0;
        if (strcmp(s, pal) == 0)
            std::cout << "corect";
        else
            std::cout << "incorect";
    }
    return 0;
} 

C++版本:

#include <iostream>
#include <string>
int main()
{
    std::string str;
    if (std::getline(std::cin, str))
        std::cout << (str == std::string(str.crbegin(), str.crend()) ? "corect" : "incorect") << std::endl;
    return 0;
}

为了完整起见,因为 OP 在风格上更像是 C 的愿望,这里有一种使用循环检测 C 中的回文的方法:

#include <stdio.h>
#include <stdlib.h>
int is_palindrone(const char *str)
    {
    const char *first, *last;
    first=last=str;
    while(*last) last++;
    last--;
    while(first < last && *first==*last) { first++; last--; }
    if(*first==*last) return 1;
    return 0;
    }