C++ Array of Characters
We can represent a text string as plain arrays of elements of a character type.
Inizialization:
1 2 3 4 5 6 7 8 9 10 | ... char myword[] = { 'H' , 'e' , 'l' , 'l' , 'o' , '\0' }; ... char myword[] = "Hello" ; ... myword[0] = 'B' ; myword[1] = 'y' ; myword[2] = 'e' ; myword[3] = '\0' ; ... |
Working example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | // strings and NTCS: #include <iostream> #include <string> using namespace std; int main () { char question1[] = "What is your name? " ; string question2 = "Where do you live? " ; char answer1 [80]; string answer2; cout << question1; cin >> answer1; cout << question2; cin >> answer2; cout << "Hello, " << answer1; cout << " from " << answer2 << "!\n" ; return 0; } |
The result is:
What is your name? Homer
Where do you live? Greece
Hello, Homer from Greece!