c++ - 为什么 usernametwo 总是被跳过?

标签 c++ io cin getline

我正在尝试学习 C++,无论如何我都在使用 if 语句。

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

为什么?

这是我的代码:

#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.\n\n";
    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.\n\n";
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.\n\n";
    cout << "Hello may I know your full name ? : ";
    cin.ignore();
    getline ( cin, usernametwo, '\n');

关于c++ - 为什么 usernametwo 总是被跳过?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23054828/

相关文章:

javascript - 如何与来自 Node.js 进程的 C++ 程序输入流进行交互?

c++ - 进行非递归制作的正确方法?

c++ - SDL_ttf 不会渲染

python - Python中的线程占用过多的CPU

java - 在结束后不关闭 InputStream 有什么意义?

c++ - 为什么我在 cin 上出现段错误?

c++ - cin.get() 循环

c++使用const变量定义数组大小

c++ - 在 C++ 中播放声音......但是,游戏在播放声音时停止......我怎样才能阻止这种滞后?

java - 如何使用JSP将excel表中的数据输入到mysql数据库中? JSP + Servlet + MySQL 项目