0

I am using friend function with istream and trying to take multiple inputs. But if i enter a space in the first input, it misses the second input(second input becomes whatever is entered after the space) and moves to asking for third input. Why is that happening, how to fix this. I tried to use cin.ignore() before second and third inputs but it doesn't work.

Class Declaration

class Data
{
private: 
 char name[20]; 
 char address[30]; 
 char city[15]; 
 long zip;   
public:
 friend istream& operator>>(istream& is, Data& i);
 friend ostream& operator<<(ostream& os, Data& obj);    
};

Class Definition

#include "Data.h"
using namespace std;

ostream& operator<<(ostream& os, Data& obj)
{   
 os << "Name: " << obj.name << endl;
 os << "Address: " << obj.address << endl;
 os << "City: " << obj.city << endl;
 os << "Zip: " << obj.zip << endl;

 return os;
}

istream& operator>>(istream& is, Data& obj)
{
 cout << "Name: ";
 is >> obj.name;
 cout << "Address: ";
 is >> obj.address;
 cout << "City: ";
 is >> obj.city;
 cout << "Zip: ";
 is >> obj.zip;

 return is;
}

Main

#include <iostream>
#include "Data.h"

using namespace std;
int main()
{
 Data d;
 cin>>d;
}
Sarmad Asif
  • 89
  • 1
  • 10
  • May be this post is helpful for you: [Why does reading a struct record fields from std::istream fail, and how can I fix it?](http://stackoverflow.com/questions/23047052/why-does-reading-a-struct-record-fields-from-stdistream-fail-and-how-can-i-fi) – πάντα ῥεῖ Mar 29 '15 at 13:17
  • that doesn't help. Can you please specify the exact problem? – Sarmad Asif Mar 29 '15 at 14:26
  • Well, to read string inputs, that contain space characters, you need to use `getline()`. That's what's essentially answered in the linked post. – πάντα ῥεῖ Mar 29 '15 at 14:29

0 Answers0