Monday, May 24, 2010

A C++ Question ? How to read a 2 letter character in an input.?

I have to create a program that reads in characters until the user enters the correct two- character sequence= (cs) to open door.





Sample Data:


cs = Door opens





ccs=Door opens





fkcds=Door doesn't open





kasfcsgd=Door opens





I have to use While Loop. but I need Answers what to put in -





My code:


/*====================================...





#include %26lt;iostream.h%26gt;





void main()


{


char ch;


int done;





cout %26lt;%26lt; endl %26lt;%26lt; "You have before you a closed door." %26lt;%26lt; endl;





while(done)


{


cout%26lt;%26lt;"Enter a sequence of letters: ";


cin%26gt;%26gt;ch;





if()


}





cout %26lt;%26lt; "The door opens. Congratulations!" %26lt;%26lt; endl;


}





/*====================================...





It is not Finished, It is just a shell I made to help.

A C++ Question ? How to read a 2 letter character in an input.?
You have to keep track of the previous characters. It depends a little bit if you want the user to have to hit enter first or you want to know right when the correct keys are pressed.





If hitting characters then enter is what you want:


#include %26lt;string%26gt;





cout %26lt;%26lt; "enter stuff\n";


string in;


cin %26gt;%26gt; in;


if (in.find("cs") != string::npos)


{


// found it


}








If you want to do something without waiting for enter:





cout%26lt;%26lt;"Enter a sequence of letters: ";


char prev = 0, curr = 0;


while(prev != 'c' || curr != 's')


{


prev = curr;


curr = getch();


}


//when loop exits, prev == 'c' and curr == 's'





You can also do it with string class. this is nice as the length of the check increases.





cout%26lt;%26lt;"Enter a sequence of letters: ";


string in;


while(in != "cs")


{


char ch = getch();


in = in.substr(1); // trims off left character


in.push_back(ch)


}
Reply:after #include%26lt;iostream.h%26gt;


put #include%26lt;string.h%26gt; or #include%26lt;string%26gt; (depends on the version)





Then to add a string variable just put:





string dooropen;





(dooropen is an example)





string is a variable like any other





PS What program do you use for C++ coding...i'm trying to find one...email me...


No comments:

Post a Comment