【问题标题】:How to create and return string from function?如何从函数创建和返回字符串?
【发布时间】:2018-05-24 10:27:52
【问题描述】:

想从一个函数中生成一个字符串,以便格式化一些数据,所以函数应该返回一个字符串。

试图做“明显”,如下所示,但这会打印垃圾:

#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;
}

我认为这是因为在函数中定义的用于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;
}

【问题讨论】:

  • 使用std::string?
  • 或者您可以添加using namespace std。它是 C++ 标准库,它是类和函数的集合。内置的 C++ 库例程保存在标准命名空间中。这包括 cout、cin、string、vector、map 等内容。

标签: c++ string function


【解决方案1】:

不要为那些 20 世纪初的东西而烦恼。到上个世纪末,我们已经有了std::string,这很简单:

#include <iostream>
#include <string>

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

int main()
{
    std::cout << hello_world();
}

【讨论】:

  • 感谢您的建议;接受了另一个答案,因为它更接近实际应用程序。
【解决方案2】:

你正在编程。这还不错,但是您的问题是关于 所以这是您提出的问题的解决方案:

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;
}

【讨论】:

    【解决方案3】:

    最好的解决方案是使用std::string。但是,如果必须使用数组,那么最好在调用函数中进行分配(本例中为main()):

    #include <iostream>
    #include <cstring>
    
    void hello_world(char * s)
    {
        memcpy(s, "Hello world\n", 13);
    }
    
    int main(void)
    {
        char mys[13];
        hello_world(mys);
        std::cout<<mys;
        return 0;
    }
    

    【讨论】:

      【解决方案4】:

      不过,如果你想编写纯 C 代码,will 可以做类似的事情。

      #include <stdio.h>
      #include <stdlib.h>
      #include <string.h>
      
      char *HelloWorld(char *s, int size)
      {
              sprintf(s, "Hello world!\n");
              return s;
      }
      
      int main (int argc, char *argv[])
      {
              char s[100];
      
              printf(HelloWorld(s, 100));
      
              return 0;
      }
      

      【讨论】:

      • memset 有什么用?没关系。此外,如果 size 太小,sprintf 会导致缓冲区溢出。
      • 你说的完全正确,它没有任何理由。让我编辑一下。
      猜你喜欢
      • 2018-04-25
      • 2022-10-14
      • 1970-01-01
      • 2015-02-24
      • 2016-04-30
      • 2010-12-23
      • 2016-11-17
      • 1970-01-01
      相关资源
      最近更新 更多