'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;
}
Solution 1:[1]
You shouldn't need the char variable. I removed it and the below worked.
#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;
}
Are you wanting to use the char variable for a specific reason?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CHolladay |
