0

我已经做 C++ 两个星期了,我正在创建一个非常简单的程序,它允许用户输入他们的名字,然后输出全名,这是代码;

#include <iostream>
#include <string>

using namespace std;

int main ()
{
    string first ;
    string middle ;
    string last;

    cout << "What is your firstname?" << endl;
    getline(cin, first);
    cout << "Your firstname is ";
    first = first;
    cout << first << endl;
    cout << endl;

    cout << "What is your middle name?" << endl;
    getline(cin, middle);
    cout << "Your middle name is ";
    middle = middle;
    cout << middle << endl;
    cout << endl;

    cout << "What is your lastname?" << endl;
    getline(cin, last);
    cout << "Your lastname is ";
    last = last;
    cout << last << endl;
    cout << endl;

    cout << "Your full name is " <<  first + middle + last << endl;

    system ("pause");
    return 0;
}

我遇到的问题是它不会在最后一个 cout 中输出空格

cout << "Your full name is " <<  first + middle + last << endl;

任何帮助,将不胜感激!谢谢。

4

3 回答 3

3

将您的输出线更改为

cout << "Your full name is " <<  first << " " << middle << " " << last << endl;
于 2012-10-25T09:39:41.083 回答
0

那是因为你没有告诉它在我认为你想要它们的地方写空间。

我的猜测是你得到的空间就好了

"Your full name is "

那么你想要你和字符串之间first的空格吗middlelast但是你永远不会在那里添加任何空格。

看起来像的部分

<<  first + middle + last <<

必须更改为包含空格

<<  first + " " + middle + " " + last <<

所以你最后的整个 cout 应该是

cout << "Your full name is " <<  first + " " + middle + " " + last << endl;
于 2012-10-25T09:43:59.040 回答
0
#include <iostream>
#include <string>

using namespace std;

int main ()
{
    string first ;
    string middle ;
    string last;

    cout << "What is your firstname?\n";
    getline(cin, first);
    cout << "Your firstname is " << first << "\n\n";

    cout << "What is your middle name?\n";
    getline(cin, middle);
    cout << "Your middle name is " << middle << "\n\n";

    cout << "What is your lastname?\n";
    getline(cin, last);
    cout << "Your lastname is " << last << "\n\n";

    cout << "Your full name is " <<  first +" "+ middle +" "+ last << "\n\n";

    system ("pause");
    return 0;
}
于 2012-10-25T09:46:31.503 回答