簡體   English   中英

如何從函數創建和返回字符串?

[英]How to create and return string from 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;
}

我認為這是因為函數中定義的用於res變量的堆棧上的內存在值寫入之前就被覆蓋了,也許是在printf調用使用堆棧時。

如果我移動char res[13]; 在函數外部,從而使其成為全局函數,然后起作用。

那么答案是擁有可用於結果的全局char緩沖區(字符串)嗎?

也許做類似的事情:

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

不要理會20世紀初期的東西。 在上個世紀末,我們已經有了std::string ,這很簡單:

#include <iostream>
#include <string>

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

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

您正在編程 不錯,但是您的問題是關於因此這是您提出的問題的解決方案:

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

最好的解決方案是使用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;
}

不過,如果您想編寫純C代碼,則可以執行類似的操作。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM