|
Strings
|
|
A string is an array of characters. In order to get text from a user you must use a string. Strings work a bit different from other arrays though, here we will look into the different funcitons used for strings. Here is an example:
|
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
int main(){
char myArray[50];
cout << "Whats the password? ";
cin.getline( myArray, 50, '\n');
if( !strcmp( myArray, "cheesecake")){
strcat( myArray, " is correct! Access granted!\n");
} else {
strcpy( myArray, "Invalid password!\n");
}
cout << myArray;
system("pause");
}
|
Here we begin by declaring a string of 50 characters. The first line with a new function would be "cin.getline( myArray, 50, '\n');", the first parameter getline() takes is the string you want to store the data in, next is the max amount of characters allowed, and finally what you want the string to be terminated with.
"if( !strcmp( myArray, "cheesecake")){" will check if myArray is equal to cheesecake. Notice how I used the Not operator here, this is because strcmp returns false if the condition is met. Also remember strcmp() is case sensitive!
"strcat( myArray, " is correct! Access granted!\n");" This will add " is correct! Access granted!\n" to the end of myArray, you can also place another string in place of the text in order to join two strings.
"strcpy( myArray, "Invalid password!\n");" This will replace myArray with "Invalid password!\n". Whatever was in myArray will be wiped out and replaced by the text.
|
|
|