如何从函数创建和返回字符串?

Equ*_*Dev 1 c++ string function

想从函数生成一个字符串,为了格式化一些数据,所以函数应该返回一个字符串.

试图做"明显的",如下所示,但这打印垃圾:

#include <iostream>
#include <string>

char * hello_world()
{
    char res[13];
    memcpy(res, "Hello world\n", 13);
    return res;
}

int main(void)
{
    printf(hello_world());
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我认为这是因为用于res函数中定义的变量的堆栈上的内存在写入值之前被覆盖,可能是在printf调用使用堆栈时.

如果我移出char res[13];函数,从而使它成为全局函数,那么它就可以了.

那么有一个可以用于结果的全局字符缓冲区(字符串)的答案是什么?

也许做的事情如下:

char * hello_world(char * res)
{
    memcpy(res, "Hello world\n", 13);  // 11 characters + newline + 0 for string termination
    return res;
}

char res[13];

int main(void)
{
    printf(hello_world(res));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

MSa*_*ers 9

不要为20世纪初期的事情烦恼.到上个世纪末,我们已经拥有了std::string,这很简单:

#include <iostream>
#include <string>

std::string hello_world()
{
    return "Hello world\n";
}

int main()
{
    std::cout << hello_world();
}
Run Code Online (Sandbox Code Playgroud)


nvo*_*igt 5

你正在编程.这不错,但你的问题是关于所以这是你问的问题的解决方案:

std::string hello_world()
{
    std::string temp;

    // todo: do whatever string operations you want here
    temp = "Hello World";

    return temp;
}

int main()
{
    std::string result = hello_world();

    std::cout << result << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)