如何使此"while"工作?

How can I make this "while" work?

本文关键字:工作 while 何使此      更新时间:2023-10-16

我正在阅读Bjarne Stroustrup的《编程原理和使用C Plus Plus的实践》,我读到第66页。

我正在自己尝试一些事情,我在Visual Studio上写了这个:

#include "../../std_lib_facilities.h";
int main()
{
    string first_name = " ";
    string last_name;
    int numbert = 0;
    while (cin >> last_name) {
        ++numbert;
        if (last_name > first_name)
            cout << first_name << ": plays guitar!n" << last_name << " : plays bass!n";
        }
}

我想让它做的是:当我在提示符处输入"Lennon Mccartney"时,返回:

Lennon: plays guitar!
Mccartney: plays bass!

但是我得到的是:

 :plays guitar!
Lennon: plays bass!
 :plays guitar!
Mccartney: plays bass!

我们都知道麦卡特尼弹奏贝斯。为什么我得到这个?请问我怎样才能修好它?

谢谢。

你没有得到first_name的输入,你应该使用下面的代码

    #include<iostream>
    #include<string>
    using namespace std;
    int main()
    {
        string first_name = " ";
        string last_name;
        int numbert = 0;
        while (cin >> first_name >>last_name) {
            ++numbert;
            if (last_name > first_name)
                cout << first_name << ": plays guitar!n" << last_name << " : plays bass!n";
        }
    }