Thread: how to print two different value in same line

  1. #1
    Registered User
    Join Date
    May 2017
    Posts
    129

    how to print two different value in same line

    how to print two different value in same line
    Code:
    #include <iostream>using namespace std;
    
    
    int main()
    
    
    {
    	char name[] = "Abhi";
    	  
    	int age = 17 ;
    	
    	cout << name <<endl;
    	cout << age <<endl;
    	
    	return 0;
    	
    }
    This program print in two line
    Abhi
    17
    But I want to print both in one line abhi 17


    Code:
    #include <iostream>using namespace std;
    
    
    int main()
    
    
    {
    	char name[] = "Abhi";
    	  
    	int age = 17 ;
    	
    	cout << name << " "<< age <<endl;
    	
    	
    	return 0;
    	
    }
    Is it better way for space ? How do we use space ?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    What do you mean "better"?

    It's tough to beat the simplicity of 5 characters of source code of <<" "

    There's no end of contrived methods which take much longer to type, and don't necessarily add any clarity.
    Code:
    #include <iostream>
    #include <iomanip>
    #include <cstring>
    using namespace std;
    
    int main()
    {
        char name[] = "Abhi";
        int age = 17 ;
    
        cout << left << setw(strlen(name)+1) << name << age << endl;
    
        return 0;
    }

    You could use regular c-style printf() if you wanted.

    Or even something which looks a bit like printf format strings, with the added benefit of C++ type safety.
    Type-safe 'printf-like' format class - 1.67.0
    Extremely Efficient Type-safe printf Library - CodeProject
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 06-02-2017, 04:00 PM
  2. Replies: 3
    Last Post: 03-12-2013, 09:58 PM
  3. how to open files and print line by line in shell
    By omega666 in forum Linux Programming
    Replies: 4
    Last Post: 04-15-2011, 04:54 PM
  4. Print Certain Line in C
    By mancode1009 in forum C Programming
    Replies: 7
    Last Post: 08-27-2008, 07:47 PM
  5. print line by line from a file
    By SoFarAway in forum C Programming
    Replies: 3
    Last Post: 02-18-2005, 01:36 PM

Tags for this Thread