【问题标题】:invalid conversion from `const char*' to `char*'从 `const char*' 到 `char*' 的无效转换
【发布时间】:2015-04-22 17:21:22
【问题描述】:
#include <stdio.h>
#include <string.h>
#include <conio.h>
#define SIZE 20

int main( void )
{
    int n; //number of characters to be compared
    char s1[ SIZE ], s2[ SIZE ];
    char *results_word;

    printf( "Enter two strings: " );
    gets( s1 );
    gets( s2 );
    printf( "\nEnter the number of characters to be compared: " );
    scanf( "%d", &n );

问题从这里开始

    results_word = 
                 strncmp( s1, s2, n ) > 0 ? " greater than " : 
                 strncmp( s1, s2, n ) == 0 ? " equal to " : " smaller than " ;

    printf( "\n%sis%s%s", s1, results_word, s2 );

    getche();
    return 0;
}//end function main

那么为什么 result_word 没有得到对应的字符串呢?

【问题讨论】:

  • 我认为您使用的是 C++ 编译器而不是 C
  • 您似乎在使用 Borland/Turbo C,这不是很标准的抱怨,也不支持现代 C。gets() 不安全,已被弃用。请改用fgets()。顺便说一句,你的代码看起来不错。
  • char *results_word; 更改为 const char *results_word;

标签: c++ string strcmp


【解决方案1】:

您收到的 C++ 错误消息说明了一切:

从 `const char*' 到 `char*' 的无效转换

您正在尝试将一些常量 "&lt;literal&gt;" 分配给非常量 results_word

改变

char *results_word;

成为

const char *results_word;

它会起作用的。

【讨论】:

  • 你假设是 C++ 编译器吗?
  • @ShafikYaghmour:你在 C 语言中是正确的,这不会有问题。
  • @Shinz6 然后标记 C++。答案因您使用的语言而异。
  • 这不是在 C11 中修复的吗?字符串文字现在是const char*,就像它们一直以来的样子。允许 char* 用于文字是一种兼容性黑客。
  • @ZanLynx 您正在考虑 C++11,它确实删除了该转换。在 C 中,据我所知,即使在 C11 中,字符串文字也确实具有 char [] 类型。
猜你喜欢
  • 2017-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-05
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多