如何从 C++ 中的函数返回字符串值
How can I return a string value from a function in C++
#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
中再次打印。我能看到你的程序的唯一问题是:
- 您无缘无故地使用
system("pause")
。 - 您与使用
std::
前缀或导入命名空间不一致。在这方面,我强烈建议使用std::
前缀。 - 您没有使用函数参数。
我最初只是想使用"char",但由于某种原因这不起作用。
好吧,顾名思义,char
只能存储1个字符。在:
char test = "help";
您正在尝试为大小只能存储 1 的对象分配 5 个字符 (4 +