I am unable to identify my coding error in this exercise.could please someone guide me in where to find it and what i am doing wrong? please..
this is what is expected from the program:
What is your major? computer science
What is your gpa? 3.52
computer science is very hard; why do you think
you have a gpa of 3.52?
This is what i am getting from my program:
What is your major? computer
What is your gpa? 0
computer is very hard; why do you think
you have a gpa of 0?
This is my work:
#include <iostream>
#include <string>
using namespace std;
int main() {
string major;
double gpa = 0.0;
cout<<"What is your major? ";
cin>>major;
cout<<major;
cout<<endl;
cout<<"What is your gpa? ";
cin>>gpa;
cout<<gpa;
cout<<endl;
cout<< major <<" is very hard; why do you think" <<endl;
cout<<"you have a gpa of ";
cin>>gpa;
cout<<gpa;
cout<<"?";
cout<<endl;
return 0;
}
Please any suggestions, solutions, assistance i will appreciated :) thank you in advance
Flaze07 (118): it runs but when the input on "major" has two words only one word appears, and the "gap" only comes as zero always :( so I don't know what I failed.
it runs but when the input on "major" has two words only one word appears
You have two use the getline function to read the two separate words (i.e. Computer Science)
(i.e. getline(cin, major); )
The getline function reads an entire line, including leading and embedded spaces, and stores it in a string object. The getline function looks like the following, where cin is the input stream we are reading from and inputLine is the name of the string object receiving the input.
The first problem I see is with line 9. Use std::getline(std::cin, major); instead of the "std::cin". "cin" will only extract to the first space or newline whichever comes first. So an input consisting of two or more words the "cin" will extract only the first word up to and including the first space then it will discard the space. This will leave the rest of what you entered in the input buffer for any next read to extract form the input buffer and not the keyboard.
That is why cin >> gpa; fails because "gpa" is expecting a number, but it is trying to extract a string from the input buffer.
chicofeo, Handy Andy (590), Tulu (3) : thank you for the knowledge and you guys time, you guys are absolutely right. i was missing the getline. It works perfectly.. thank you TULU!!