来自`const char *'的无效转换到`char *'

时间:2015-04-22 17:21:23

标签: c++ string strcmp

#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

那么为什么没有结果_word得到相应的字符串?

1 个答案:

答案 0 :(得分:4)

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

  

来自`const char *&#39;的无效转换到`char *&#39;

您正尝试将一些常量"<literal>"分配给非常量results_word

更改

char *results_word;

const char *results_word;

它会起作用。