C ++帮助 - getline

时间:2012-10-25 09:26:03

标签: c++ whitespace getline

我已经做了两个星期的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;

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

3 个答案:

答案 0 :(得分:3)

将输出行更改为

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

答案 1 :(得分:0)

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

我的猜测是你在

中获得了很好的空间
"Your full name is "

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

看起来像

的部分
<<  first + middle + last <<

必须更改为包含空格

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

所以你最后的cout应该是

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

答案 2 :(得分: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;
}