Using the STL Library in C++, part 1

All of us, programmers have thought about an easier way to get a better and faster result. The STL allows us to make it. For example, to insert characters we had to make an array:

#include <iostream> //preprocessor directive

using namespace std;  //namespace which allows us to use console out, console in & endl

int main()

{

char myArray[25];   //here we have to insert the length of our array

cin >> myArray;  // input of our string

cout << myArray; //output of our string

return 0;

}

If we insert a two-words sentence, we will see as a return, only one part of it – the first word. How to correct it?

We have to use cin.get. Let’s see:

#include <iostream>

using namespace std;

int main()

{

char myArray[25];

cin.get(myArray, 24);

cout << myArray;

return 0;

}

And if we want to copy one string to another by using arrays it is not the best way to do it:

char myArray[] = "Hello my friend";

char myArray2[] = {'\0'};

strcpy(myArray2, myArray);

cout << myArray2 << endl;

You can see that the result is good. However there are problems – you have to remember that to copy one to another you have to use a special instruction strcpy and the order of your arrays. By using the STL Library you can solve it:

#include <iostream>

#include <string>

using namespace std;

int main()

{

string myString;  //create string

getline(cin, myString);  //similar to cin.get

cout << endl;

string myString2;

getline(cin, myString2);

cout << endl;

myString += myString2;  //connecting one string to the another

cout << myString

string myString3(myString); //copy content of myString to myString3

return 0;

}

I think that using strings is more comfortable and better to learn. Moreover, in these days most of programmers use STL.

MJ

Zostaw komentarz

Wprowadź swoje dane lub kliknij jedną z tych ikon, aby się zalogować:

Logo WordPress.com

Komentujesz korzystając z konta WordPress.com. Wyloguj /  Zmień )

Zdjęcie na Google+

Komentujesz korzystając z konta Google+. Wyloguj /  Zmień )

Zdjęcie z Twittera

Komentujesz korzystając z konta Twitter. Wyloguj /  Zmień )

Zdjęcie na Facebooku

Komentujesz korzystając z konta Facebook. Wyloguj /  Zmień )

w

Connecting to %s