为什么用户名二总是被跳过

Why does usernametwo always get skipped?

本文关键字:用户 为什么      更新时间:2023-10-16

我正在努力学习C++,无论如何我都在if语句上。

我编写了一个程序,询问两个用户的全名和年龄(虚构用户),它询问用户1的姓名和年龄,以及用户2的年龄,但不知何故,询问用户2的姓名被跳过,最终询问用户2年龄

为什么?

这是我的代码:

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string usernameone;
    string usernametwo;
    int age1;
    int age2;
    //ask the users their name and age
    cout << "Hi may I know your full name ? : ";
    getline ( cin, usernameone, 'n');
    cout << "nHello " << usernameone << " May I know now whats your age ? : ";
    cin >> age1;
    cout << "Ok thanks for the information, now may I talk to the other user ? thanks.nn";
    cout << "Hello may I know your full name ? : ";
    getline ( cin, usernametwo, 'n');
    cout << "nHello " << usernametwo << " May I know now whats your age ? : ";
    cin >> age1;
    if(age1 < age2)
    {
        cout << "looks like " << usernameone << " is older than " << usernametwo;
    }
    else
    {
        cout << "ok " << usernametwo << " is older than " << usernameone;
    }
    if(age2 && age1 >= 100)
    {
        cout << "your both lying your age can't be 100 and above";
    }
    cin.ignore();
    cin.get();
    return 0;
}
cin >> age1;
cout << "Ok thanks for the information, now may 
         I talk to the other user ? thanks.nn";
cout << "Hello may I know your full name ? : ";

'n'留在输入流中,并且您正在下一次读取中读取它

getline ( cin, usernametwo, 'n');

您可以使用以下选项忽略此字符:

    cin >> age1;
    cout << "Ok thanks for the information, now may 
             I talk to the other user ? thanks.nn";
    cout << "Hello may I know your full name ? : ";
    cin.ignore();
    getline ( cin, usernametwo, 'n');
相关文章: