How to receive input with spaces?

I my main function, the use is asked to input certain information( M#,Mesh#, and object name), however the questions are not displaying correctly on the screen.This is what the output looks like:

Enter Object name: Enter M#:

What am I doing wrong?

Here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
int main(){
     string fileName;
     cout<<"Enter file name: ";
     cin>> fileName;
     bool value = true;
     string objectName;
     int Mnum,contd;
     int Meshnum;
     materialList ml; //(list<Item> test);
     while(value){
         std::cout<< "Enter Object name: ";
         std::getline(std::cin,objectName);
         cout<<" Enter M#: ";
         cin>> Mnum;
         cout<<"Enter Mesh#: ";
         cin>> Meshnum;
         //Item second= Item(objectName,Mnum,Meshnum);
         ml.add(Item(Mnum,objectName,Meshnum));
         cout<< "press 1 to continue or 2 to exit: ";
         cin>>contd;
         if(contd==2){
             value = false;
         }else if(contd==1){
             value=true;
         }
        
     }
     ml.Print();
     ifstream inFile;
     
     ml.search(inFile,fileName);
     
     
     //Item test= Item("door",34,50);
     //itemList = 
	 
     //ml.add(test);
     //ml.Print();

 }
Last edited on
cin>> fileName;
you pressed <Return> after writing the filename, you need to discard the '\n' character from the input buffer
1
2
cin>> fileName;
cin.ignore();


same for cin>>contd;
>> ignores leading white space and stops when a trailing white space is found (or extraction failure) but doesn't remove the found white space.

getline() extracts data until the specified delim is found (default '\n') and removes the delim. It doesn't skip leading white space.

So if a cin is used first, the terminating \n is left in the buffer which is found by getline() as terminating the data get. If you mix >> with getline(), you need to also remove the '\n' left by >> before the getline(). This is usually done by .ignore(). Often used as .ignore(1000, '\n') in case there are more than one white space chars left after the >> extraction.
Topic archived. No new replies allowed.