如何为一个函数分配多个字符串变量?

时间:2019-07-02 14:03:14

标签: c++

基本上,我希望函数stringFeatures输出变量texttext1text2的大小和容量。我试图将texttext1text2分别分配给变量,以减少代码的混乱度,但是我没有取得任何成功。我将如何处理?谢谢

#include <iostream>
#include <string>
using namespace std;

int main() {
string text = "Banana";
string text1 = "Orange";
string text2 = "Grapes";
string variable = text + text1 + text2;


void stringFeatures (string variable);
{
    cout << "Size: " << variable.size();
    cout << "Capacity: " << variable.capacity();
}

cout << variable << endl;

}

我希望输出分别是每个字符串的大小和容量,但是我不知道如何分别分配每个变量,我只是将所有变量组合在一起,而不是字符串variable中所示因为我不知道该怎么办

3 个答案:

答案 0 :(得分:4)

我已经修复并注释了您的代码,使其可以按您的预期工作:

#include <iostream>
#include <string>

// That's the function's definition (body), it should not be inside another function
void stringFeatures (std::string variable) // <-- no ; in a function definition
{
    std::cout << "Size: " << variable.size();
    std::cout << " Capacity: " << variable.capacity();
    std::cout << "\n"; // Additional newline for clarity
}

int main() {
    std::string text = "Banana";
    std::string text1 = "Orange";
    std::string text2 = "Grapes";

    // Call the function with each string
    stringFeatures(text);
    stringFeatures(text1);
    stringFeatures(text2);
}

请注意,我还删除了using namespace std;,请参阅this Q&A关于这是一个坏习惯的原因。

但是了解代码中实际发生的事情也很有趣:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string text = "Banana";
    string text1 = "Orange";
    string text2 = "Grapes";
    string variable = text + text1 + text2;

    // This declares a stringFeatures function that is not used at all
    void stringFeatures (string variable);

    // This is completely separate from the function declaration above,
    // which ended at the semicolon.
    // It's a plain code block which only acts on the local variable `variable`.
    {
        cout << "Size: " << variable.size();
        cout << "Capacity: " << variable.capacity();
    }

    cout << variable << endl;
}

答案 1 :(得分:1)

如果我理解正确,您想调用该函数3次,并传递要显示其容量和大小的变量。看一下下面的代码:

#include <iostream>
#include <string>
using namespace std;

void stringFeatures(string variable)
{
    cout << "Size: " << variable.size();
    cout << "Capacity: " << variable.capacity();
}

int main() 
{
    string text = "Banana";
    string text1 = "Orange";
    string text2 = "Grapes";

    stringFeatures(text);
    stringFeatures(text1);
    stringFeatures(text2);  
}

答案 2 :(得分:1)

喜欢吗?

void MyFunction(string variable) {
    cout << variable.size();
    cout << variable.capacity();
}

int main() {
    string text1 = "Banana";
    string text2 = "Orange";
    string text3 = "Grapes";

    MyFunction(text1);
    MyFunction(text2);
    MyFunction(text3);
}