cout and cin C++ Console Application

All tutorials created in C++ to be posted in here.
1 post Page 1 of 1
Contributors
User avatar
MrAksel
C# Coder
C# Coder
Posts: 1758
Joined: Fri Mar 26, 2010 12:27 pm

This tutorial will be about the std::cout object to output text to the console, and the std::cin object to input text from the console. You will also see how to use the 'arguments' passed to the program when executed. To use std::cin, you will need to create the buffer to where the characters are stored, which includes memory management.
I am using Visual Studio for this tutorial.
So make a new Win32 Console Application, just press Finish if a wizard comes up. Then in your main file include "stdafx.h" and <iostream>. Then use the std namespace
Code at this stage:
Code: Select all
#include "stdafx.h" //Included by default when you create a project
#include <iostream> //This is where cout and cin is declared

using namespace std; //same as Imports in Visual Basic
If you are using Visual Studio, the main function will be called _tmain. Inside your main function, paste the following:
Code: Select all
	cout<<"Parameters: "<<argc<<"\n";
	for(int i = 0; i < argc; i++) 
	{
		cout<<"Parameter '"<<i<<"' is "<<argv[i]<<"\n";
	}
	cout<<"Write something\n";
	char* in = (char*)malloc(255);
	cin>>in;
	cout<<"You wrote: "<<in<<"\n";
	system("PAUSE");
	delete in;
	return 0;
First get familiar with cout object. It is an instance of ostream. The << adds a string/integer to the end of the stream. cout is the default output stream, therefore it is displayed on the console. "\n" is short for NewLine. You could have "\r\n" which is short for CarriageReturn + NewLine, but both work fine to make a new line.
So it adds the string "Parameters: " then it adds 'argc' (argument count) which is the number of arguments passed then it adds the NewLine.
In the for loop it simply displays the value of each argument.
I assume you now know what line 5 does, so ill skip that.
The memory management comes first at line 6. It creates a 255 bytes large buffer that is converted to a char buffer. So the maximum chars you can input is 255.
the cin is an instance of istream (input stream). It is the default input stream where all your console input is passed to. The >> outputs data from the stream to the char buffer.
After that we show the user what he wrote and waits for a final key to close the program. But we forgot a thing; clean up after us. Therefore we use the delete function to delete the buffer and prevent memory loss.
You do not have the required permissions to view the files attached to this post.
LMAOSHMSFOAIDMT
Laughing my a** of so hard my sombrero fell off and I dropped my taco lmao;


Over 30 projects with source code!
Please give reputation to helpful members!

Image
Image
1 post Page 1 of 1
Return to “C++ Tutorials”