Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

io

cout

cin

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

like image 229
Gary Host Avatar asked Dec 12 '25 14:12

Gary Host


2 Answers

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:

  • a semicolon (Live Demo):

    int p1;
    cout << "Person 1:";
    cin >> p1;
    
  • the comma operator (Live Demo):

    int p1;
    cout << "Person 1:", cin >> p1;
    
like image 151
Remy Lebeau Avatar answered Dec 14 '25 04:12

Remy Lebeau


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.

like image 22
M.M Avatar answered Dec 14 '25 03:12

M.M