Gary Host
Gary Host

Reputation: 31

How do I put a cout and a cin on the same line?

I am trying to put a cout and a cin on the same line as so cout << "Person 1:" << cin >> int p1;. Does anybody know a way that I could do the same thing successfully?

I'm using C++ on repl.it if that helps

Upvotes: 2

Views: 24993

Answers (6)

111
111

Reputation: 1

Just press space instead of Enter.

Upvotes: 0

Remy Lebeau
Remy Lebeau

Reputation: 596307

The code you showed will not work, because you can't pass a std::istream (like std::cin) to operator<< of a std::ostream (like std::cout). You need to separate the expressions, separating them by either:

Upvotes: 6

Connor Smith
Connor Smith

Reputation: 15

I have no clue why you would want to do it this want to do it this way, but I am still gonna try and answer you.

You can overload the << operator for istream to complete the task, and then use istream's unget() before returning istream, which causes the input to go to both cout and then into the p1 variable. This can be seen in my example code below:

#include <iostream>
using namespace std;
istream &operator<<(ostream& out, istream& in){
  int a = 0;
  in >> a;
  out << a;
  in.unget();
  return in;
}

int main()
{
  int p1;
  cout << "Person 1: " << cin >> p1;
  cout << "Test: " <<  p1 << endl;
  return 0;
}

Please note that this overload is specifically for integers and will not work with other data types. You may see this code in action here, but note that the true output is actually

Person 1: 5
5Test: 5

Upvotes: 0

M.M
M.M

Reputation: 141576

You can write:

int p1 = (cin >> (cout << "Person 1: ", p1), p1);

This would be a terrible idea in terms of writing clear code, I'm mainly posting it in response to several others who said that it is not actually possible.

Upvotes: 5

Grigory
Grigory

Reputation: 158

All stream operators are return stream objects. cin and cout are global instance of istream and ostream classes. When you use operator<</operator>>, they are return stream objects to provide chaining.

When you write something like std::cout << "he" << 11 << 'o', it's provide calling std::cout << "he" at first (in case of left associativity of operator<<). It complete it's code (print "he" on stdout) and return left argument, so now the original line is std::cout << 11 << 'o', then again will call the most left operator<< with its args: std::cout << 11, on console will "he11" now, and the line can be interpreted as std::cout << 'o'.

The returning of left arg stream object provide chaining even on your objects. This work the same with input operators. stream >> x >> y; mean read from stream stream value, store it to x then read next value, store it in y.

Upvotes: 0

gsamaras
gsamaras

Reputation: 73366

You cannot do that in a single command/statement.

You need to do it like this:

int p1;
cout << "Person 1:";
cin >> p1;

Upvotes: 0

Related Questions