如何从 C++ 中的函数返回字符串值

How can I return a string value from a function in C++

本文关键字:函数 返回 字符串 C++      更新时间:2023-10-16
#include <iostream>
#include <string>
using namespace std;
std::string dispCard(int card)
{
    string textCard = "help";
    //cout << textCard;
    system("pause");
    return textCard;
}
int main()
{
    // Using this area to test functions for now
    cout << dispCard(14);
    return 0;
}

取消注释cout行实际上会显示该值。但是我无法返回字符串中的值。

老实说,我不知道为什么这不起作用。我最初只是想使用"char",但由于某种原因这不起作用。

Visual Studio不喜欢:

char test;
test = "help";

它强调了"="。

现在,我只想从函数返回一个字符串值。我需要它做更多的事情,但这是目前的主要问题。

取消注释 cout 行实际上会显示字符串。但不返回字符串。

程序同时打印并返回字符串,并在 main 中再次打印。我能看到你的程序的唯一问题是:

  1. 您无缘无故地使用system("pause")
  2. 您与使用 std:: 前缀或导入命名空间不一致。在这方面,我强烈建议使用std::前缀。
  3. 您没有使用函数参数。

我最初只是想使用"char",但由于某种原因这不起作用。

好吧,顾名思义,char只能存储1个字符。在:

char test = "help";

您正在尝试为大小只能存储 1 的对象分配 5 个字符 (4 + )。这就是编译器抱怨的原因。

我认为您需要将 int 传递给您的函数并以字符串形式返回。要进行此转换,您需要这样的东西:

std::ostringstream stm;
stm << yourIntValue;
std::string s(stm.str());

或者这个:

char bf[100];
sprintf(bf, "%d", yourIntValue);
std::string s(bf);

如果你把这个代码片段放在一个函数中,那么你也可以接受一个int参数,将其转换为std::string,并返回std::string,如其他人所示。

您需要

做的是将函数的返回类型声明为 std::string,然后返回字符串对象、可以隐式转换为字符串对象的东西或显式构造字符串对象的东西。

例:

std::string foo(){
    return "idkfa"; //return C-style string -> implicitly convertible to string
    return {"idkfa"}; // direct initialization of returning std::string
    return std::string("idkfa"); //return explicitly constructed std::string object
}

还要注意C风格的字符串是char*类型(C风格的字符串基本上是一个chars数组,最后一个元素是,即0)。

你的代码工作得很好,尽管system("pause")是完全冗余和毫无意义的,应该删除。事实上,这可能会让您感到困惑。