Newline in istream

I have the following code and was wondering if there's a function that can be used in istream that will give a newline in output. For instance, having a newline between feet and inches in istream.

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
#include <iostream>
using namespace std;
 
class Distance {
   private:
      int feet;             // 0 to infinite
      int inches;           // 0 to 12
      
   public:
      // required constructors
      Distance() {
         feet = 0;
         inches = 0;
      }
      Distance(int f, int i) {
         feet = f;
         inches = i;
      }
      friend ostream &operator<<( ostream &output, const Distance &D ) { 
         output << "F : " << D.feet << " I : " << D.inches;
         return output;            
      }

      friend istream &operator>>( istream  &input, Distance &D ) { 
         input >> D.feet >> D.inches;
         return input;            
      }
};

int main() {
   Distance D1(11, 10), D2(5, 11), D3;

   cout << "Enter the value of object : " << endl;
   cin >> D3;
   cout << "First Distance : " << D1 << endl;
   cout << "Second Distance :" << D2 << endl;
   cout << "Third Distance :" << D3 << endl;

   return 0;
}

Last edited on
> used in istream that will give a newline in output.
don't quite understand your question
istream is used for input
as you are reading numbers, whitespace will be ignored
Yes.

1
2
#include <iostream>
#include <limits> 
 
std::cin.ignore( std::numeric_limits <std::streamsize> ::max(), '\n' );

I personally like to wrap it up into a manipulator.

1
2
3
#include <iomanip>
#include <iostream>
#include <limits> 
1
2
3
4
5
template <class CharT, class Traits>
std::basic_istream <CharT, Traits> & endl( std::basic_istream <CharT, Traits> & ins )
{
  return ins.ignore( std::numeric_limits <std::streamsize> ::max(), '\n' );
}
1
2
3
4
5
  int n;
  {
    std::cout << "n? ";
    std::cin >> n >> endl;
  }

Enjoy!
I'll try to explain better. The code above has the following output:

1
2
3
4
5
6
Enter the value of object :
70
10
First Distance : F : 11 I : 10
Second Distance :F : 5 I : 11
Third Distance :F : 70 I : 10


I want to know if there is some type of function for spacing to use in istream(not main function, I know how to do it in main function) to make my output look like this:

1
2
3
4
5
6
7
8
Enter the value of object :
70
10
                      //this is what I'm trying to do

First Distance : F : 11 I : 10
Second Distance :F : 5 I : 11
Third Distance :F : 70 I : 10
Is there an easier way of doing it?
As ne555 already pointed out, input and output are not the same thing.

If you want spaces, print some newlines. That’s maybe 15 or 20 characters worth of typing...
Registered users can post here. Sign in or register to post.