从函数....限制中返回一个字符串?

时间:2013-03-21 19:16:35

标签: c++ c string

我很想知道我有这个特殊的代码

char* usage()
     {
         static char errors[] = {"Sorry Invalid Option entered\nPlease Enter an appropriate option"};        
         return errors;
     }

我已正确调用该函数,它可以实现我想要的功能。然而,在我这样做的时候......我得到了大量的错误。

char* usage()
     {
         static char errors[] = {"Sorry Invalid Option entered\n
                                 Please Enter an appropriate option"};        
         return errors;
     }

我所做的就是将第二行放在下面一排我得到错误。现在,我想知道两者之间有什么区别?我似乎在两个字符数组中输入了相同的参数。是不是因为我没有为阵列提供malloc空间?

2 个答案:

答案 0 :(得分:9)

C和C ++不支持多行文字,但你可以使用它:

char* usage()
{
     static char errors[] = {"Sorry Invalid Option entered\n"
                             "Please Enter an appropriate option"};        
     return errors;
}

请注意额外的报价!

答案 1 :(得分:5)

在C(我不知道C ++)中,您可以使用引号连接字符串(此连接由预处理器完成)这一事实在多行中编写字符串

char test[] = "one " "two" " " "<= that's a space :)" "\n"
              "three and four\n"
              "five etc and so on\n"
              "\n"
              "for ever and ever ...\n";

注意:除最后一行外没有分号。