【问题标题】:How to return a string from a C++ function? [closed]如何从 C++ 函数返回字符串? [关闭]
【发布时间】:2013-05-13 07:58:56
【问题描述】:

这是一个简单的示例程序:

#include <iostream>
#include <string>

using namespace std;

string replaceSubstring(string, string, string);

int main()
{
    string str1, str2, str3;

    cout << "These are the strings: " << endl;
    cout << "str1: \"the dog jumped over the fence\"" << endl;
    cout << "str2: \"the\"" << endl;
    cout << "str3: \"that\"" << endl << endl;
    cout << "This program will search str1 for str2 and replace it with str3\n\n";

    cout << "The new str1: " << replaceSubstring(str1, str2, str3);

    cout << endl << endl;
}

string replaceSubstring(string s1, string s2, string s3)
{
    int index = s1.find(s2, 0);

    s1.replace(index, s2.length(), s3);

    return s1;
}

它可以编译,但是该函数不返回任何内容。如果我将return s1 更改为return "asdf",它将返回asdf。如何使用此函数返回字符串?

【问题讨论】:

  • 你实际上并没有初始化你的字符串变量。
  • 为什么觉得返回字符串有问题?检查函数内部字符串的值。
  • 您输出的文本只是给编译器的文本——它不会试图弄清楚该文本的含义,也不会为您兑现您的承诺。毕竟,也许你是想对用户撒谎。
  • 所以我猜你会因为犯了一个愚蠢的错误而被否决?哦,好吧。
  • @fredsbend - 反对票主要意味着这不是一个有趣的问题。对于想要赢得一些声誉的新手来说,这并不好玩,但大多数新手问题甚至对大多数其他新手来说都不感兴趣 - 他们会犯自己的错误,如果他们犯了错误,他们将无法找到你的问题反正同样的错误。通常的术语是“过于本地化”。你得到了帮助 - 不要太担心高分表。

标签: c++ string return-value


【解决方案1】:

为你的字符串分配一些东西。这肯定会有所帮助。

【讨论】:

    【解决方案2】:

    你从不给main中的字符串任何值,所以它们是空的,因此很明显该函数返回一个空字符串。

    替换:

    string str1, str2, str3;
    

    与:

    string str1 = "the dog jumped over the fence";
    string str2 = "the";
    string str3 = "that";
    

    另外,你的replaceSubstring 函数有几个问题:

    int index = s1.find(s2, 0);
    s1.replace(index, s2.length(), s3);
    
    • std::string::find 返回std::string::size_type(又名size_t)而不是int。两个区别:size_t 是无符号的,并且它不一定与 int 的大小相同,具体取决于您的平台(例如,在 64 位 Linux 或 Windows 上,size_t 是无符号的 64 位,而 int 是有符号的 32 位) .
    • 如果s2 不是s1 的一部分会怎样?我会把它留给你来找到解决这个问题的方法。提示:std::string::npos ;)

    【讨论】:

    • 是的。晚了。骨头动。谢谢。
    • @fredsbend:我刚刚在您的代码中添加了另一个问题(与您的问题无关)。查看我的编辑。
    • 我已经使用 while 循环解决了第二点,如果 index 大于 s1.length(),则该循环会中断。效果是它现在将所有s2 实例替换为s3。我不熟悉size_t,虽然我遇到过。
    • @fredsbend:if 就足够了,不需要使用while。至于size_t,重要的是你要习惯它。 :) 为避免将来出现这种情况,我最好的建议是系统地验证您使用的每个 API 的文档,直到您对它感到满意为止。 cppreference 是一个很好的地方。我知道这很乏味,但这是同时学习编写优秀代码的最佳方式。
    【解决方案3】:
    string str1, str2, str3;
    
    cout << "These are the strings: " << endl;
    cout << "str1: \"the dog jumped over the fence\"" << endl;
    cout << "str2: \"the\"" << endl;
    cout << "str3: \"that\"" << endl << endl;
    

    由此,我看到您尚未初始化 str1、str2 或 str3 以包含您正在打印的值。我可能会建议先这样做:

    string str1 = "the dog jumped over the fence", 
           str2 = "the",
           str3 = "that";
    
    cout << "These are the strings: " << endl;
    cout << "str1: \"" << str1 << "\"" << endl;
    cout << "str2: \"" << str2 << "\"" << endl;
    cout << "str3: \"" << str3 << "\"" << endl << endl;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-18
      • 1970-01-01
      • 2014-11-06
      相关资源
      最近更新 更多