Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

In this code I ask the user for inputs separated by a space, gradeOne space gradeTwo.
However, it is not functioning as intended so I added output statements at the end to see if the values were stored correctly.

If I type in: 59 95 gradeOne should be 59, temp should be ‘ ‘ and gradeTwo should be 95 but the output says gradeOne is 59, temp is 9 and gradeTwo is 5. What is happening? Thank you for any help!

#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;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

operator >> automatically skip space. Just change to:

cin>>gradeOne>>gradeTwo;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading