如何空格first_name + last_name C ++

时间:2022-10-08 23:54:27

My question is how can i use spaces between first_name and last_name after i instruct the user to input his name. I am using code blocks and I'm kinda confused. In Dev C++ i can do

我的问题是,在指示用户输入他的名字后,我如何在first_name和last_name之间使用空格。我正在使用代码块,我有点困惑。在Dev C ++中,我可以做到

   cout<<first_name<<" "<<last_name;

Now what I am doing is just practicing C++ using variables in a class. Here is my code.

现在我正在做的只是在类中使用变量来练习C ++。这是我的代码。

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

    class DanielClass
      {
     public:
        int setNameFunction(string first_name, string last_name)
        {
    cout<<"Enter your first name here: ";
    cin>>first_name;
    cout<<"Enter your last name here: ";
    cin>>last_name;
    name = first_name + last_name;
        }

        string getNameFunction()
        {

    return name;
        }

    private:
       string name;
    };


    int main()
    {

       DanielClass NameObject;
       NameObject.setNameFunction("", "");
       cout<<NameObject.getNameFunction();

       cout<<"\n\n";
       return 0;
     }

1 个解决方案

#1


You can add string literals (which is just a term for a string entered directly into the code with quotes around it -- like the " " in the second line of code below) to string variables using the '+' operator.

您可以使用“+”运算符添加字符串文字(这只是直接输入到代码中的字符串的术语,并带有引号 - 如下面第二行代码中的“”)字符串变量。

You just need to change the line that reads:

您只需要更改以下行:

    name = first_name + last_name;

to:

    name = first_name + " " + last_name;

#1


You can add string literals (which is just a term for a string entered directly into the code with quotes around it -- like the " " in the second line of code below) to string variables using the '+' operator.

您可以使用“+”运算符添加字符串文字(这只是直接输入到代码中的字符串的术语,并带有引号 - 如下面第二行代码中的“”)字符串变量。

You just need to change the line that reads:

您只需要更改以下行:

    name = first_name + last_name;

to:

    name = first_name + " " + last_name;