Question

Greetings fellas;

So after i compile the following code ,the MusicIns.shortDescription object don t want to receive any input and just switching to the next object ,what id wrong in my code ?

#include <iostream>
using namespace std;

 class Instruments{
public :
 int weight; 
 string size; 
 string name; 
 string shortDescription;
 string designation;
};


    int main(){

 Instruments MusicIns;

  cout<<"Please enter instrument name: "<<endl;
  getline(cin, MusicIns.name);
  cout<<"Please enter the size"<<endl;
  getline(cin, MusicIns.size);
  cout<<"Please enter the weight: "<<endl;
  cin>>MusicIns.weight;
  cout<<"Please enter a small description: "<<endl; 
  getline(cin, MusicIns.shortDescription);
  cout<<endl; 
  cout<<"Please describe the instrument designation: "<<endl; 
  getline(cin, MusicIns.designation); 
  cout<<endl;

   cout<<"============="<<endl; 
   cout<<MusicIns.name <<endl; 
   cout<<MusicIns.weight <<endl;
   cout<<MusicIns.designation <<endl; 
   cout<<MusicIns.shortDescription <<endl; 
   cout<<MusicIns.size <<endl; 
return 0;
};

Don t blame me too much for my level or syntax i am still noob.

P.s. Thank you in advance for any help !

Was it helpful?

Solution

After cin>>MusicIns.weight;, there is a newline remaining in the stream. So the new line will be assigned to the MusicIns.shortDescription. Add this line to ignore the newline: cin.ignore(100, '\n'); before std::getline(std::cin, MusicIns.shortDescription);

OTHER TIPS

One way you can do have "MusicIns.shortDescription" to receive an input is to do this method.

cin.get();

This method will catch any characters after you have terminated from the input.

  cout<<"Please enter instrument name: "<<endl;
  getline(cin, MusicIns.name);
  cout<<"Please enter the size"<<endl;
  getline(cin, MusicIns.size);
  cout<<"Please enter the weight: "<<endl;
  cin>>MusicIns.weight;
  cout<<"Please enter a small description: "<<endl; 
  std::getline(std::cin, MusicIns.shortDescription);
  cin.get();// new line
  cout<<endl; 
  cout<<"Please describe the instrument designation: "<<endl; 
  getline(cin, MusicIns.designation); 
  cin.get();// new line
  cout<<endl;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top