在 C++ 中,为什么我的由 space 分隔的变量输入存储不正确?

In C++, why are my variable inputs that are separated by a space being stored incorrectly?

在这段代码中,我要求用户输入由 space、gradeOne space gradeTwo 分隔的输入。 但是,它没有按预期运行,因此我在末尾添加了输出语句以查看值是否正确存储。

如果我输入:59 95 gradeOne 应为 59,temp 应为 ' ',gradeTwo 应为 95,但输出显示 gradeOne 为 59,temp 为 9,gradeTwo 为 5。这是怎么回事?感谢您的帮助!

#include <iostream>
using namespace std;
int main()
{
    int gradeOne, gradeTwo;
    char temp;
    cout<<"Please enter 2 grades, separated by a space: ";
    cin>>gradeOne>>temp>>gradeTwo;
    
    if(gradeOne < 60 && gradeTwo < 60)
        cout<<"Student Failed:("<<endl;
    else if(gradeOne >= 95 && gradeTwo >= 95)
        cout<<"Student Graduated with Honors:)"<<endl;
    else
        cout<<"Student Graduated!"<<endl;
    
    cout<<gradeOne<<endl;
    cout<<gradeTwo<<endl;
    cout<<temp<<endl;
        
    return 0;
}

运算符>>自动跳过space。只需更改为:

cin>>gradeOne>>gradeTwo;

您不需要 char 变量。我删除了它,下面的工作正常。

#include <iostream>
using namespace std;

int main()
{
    int gradeOne, gradeTwo;

    cout << "Please enter 2 grades";
    cin >> gradeOne >> gradeTwo;

    if (gradeOne < 60 && gradeTwo < 60)
        cout << "Student Failed:(" << endl;
    else if (gradeOne >= 95 && gradeTwo >= 95)
        cout << "Student Graduated with Honors:)" << endl;
    else
        cout << "Student Graduated!" << endl;

    cout << gradeOne << endl;
    cout << gradeTwo << endl;


    return 0;
}

您是否出于特定原因想要使用 char 变量?