Strings

Both of the programs below output the greeting "hello World".

1
2
3
4
5
6
7
8
9
//char array Hello World
#include<iostream>
using namespace std;
int main() {
   char greeting[]="Hello World";
   cout<<greeting<<endl;
   system("pause");
   return 0;
} //main
CODE

The first example shows storing "Hello World" as an array of characters.

1
2
3
4
5
6
7
8
9
10
//Strings: Hello World
#include<iostream>
#include<string>
using namespace std;
int main() {
   string greeting="Hello World";
   cout<<greeting<<endl;
   system("pause");
   return 0;
} //main
CODE

In the second example, we include the string class and declare the variable as a string.

Because the string class provides more flexibility and built-in functions for string handling, it is much easier to use.

NEXT: Input a name