从'char'到'const char *'的转换无效[-fpermissive](idk为什么)

时间:2017-12-29 13:43:25

标签: c++

#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 *'[-fpermissive]”无效转换。

这不是第一次遇到这个恼人的错误,我需要一些帮助。有人能解释我的代码有什么问题吗(请:)))给我一些文章/理论/一些东西来理解为什么会出现这个错误? 谢谢你,对不起,问这个愚蠢的问题。我看了1000次,仍然不明白。

3 个答案:

答案 0 :(得分:2)

除了已经指出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;
}

答案 1 :(得分:2)

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

当问题标记为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风格的char数组,并且在循环中使用reverse_iterator

答案 2 :(得分: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;
    }
相关问题