Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Why is the output not what I want it to be

–1 vote
asked May 2, 2020 by Ivana Ogunlaja (640 points)
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string subject;
    cout << "What is your favourite subject";
    cin >> subject;
    cout << "Nice",subject, "is a good subject";
    return 0;
}

output

What is your favourite subject? input maths

output Nice

2 Answers

0 votes
answered May 2, 2020 by LiOS (6,420 points)
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string subject;
    cout << "What is your favourite subject";
    cin >> subject;
    cout << "Nice " << subject << " is a good subject";
    return 0;
}
commented May 8, 2020 by FatehSingh (180 points)
We always use getline statement to store a string otherwise it will not store the letters after a space. instead of cin>>subject;
Use:
 getline(cin,subject);
0 votes
answered May 8, 2020 by FatehSingh (180 points)
You have two main errors in your program.

1). Use insert symbols before inserting anything in cout statement.

 cout << "Nice !! "<<subject<< " is a good subject";

2); If your subject name includes  a space in between then don't use cin statement to get the value from the user. because you are storing a string. Use this getline statement to get the value.

getline(cin,subject);

Use this corrected code:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string subject;
    cout << "What is your favourite subject ==> ";
    getline(cin, subject);
    cout << "Nice !! "<<subject<< " is a good subject";
    return 0;
}

OUTPUT:

 

What is your favourite subject ==> Physical Education                                                                         

Nice !! Physical Education is a good subject

I hope this will help you.
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...