Wednesday, January 23, 2008

Strings!

Ok, so I've just learned some things about strings. My first RPG was rather lame. It had no loops (only if statements) and all the code was inside main (no functions... although none were 'needed'). I've been developing a more advanced version of the same RPG to make use of constant actions such as "get" or "inv" (to fill or access the characters inventory full of deviousness). Here is a sample of code:



#include
#include


using namespace std;

int main(){

char action[50]; //para: what do you want to do?

int actionnum; //a number assigned to the action for case

while( x == 1 ){
cin.getline ( action, 50, '\n' );

if( strcmp ( action, "get" ) == 0 || strcmp ( action, "take" ) == 0 ){
actionnum = 1;
cout<<"You get some stuff.\n";
}
}
}


So this program will prompt for the string "action" (cin.getline ... ). It then checks to see if the string "action" has the text "get" inside of it. This is done with the strcmp function. "strcmp" checks to see if two strings are equal or greater than or less than. If the first string is less than the second, it will return a negative value, if they are equal, it will return zero, and if the first string is greater, it will return a positive value. The if statement here just checks to see if they are equal. If they are, the function displays some text. ("You get some stuff.")

I've tested this setup in my program and it seems to be working quite well!

No comments: