Trying to compare characters within two strings

Hi,

I am trying to compare a student's answers to an answer key, and each one is a string, containing characters of either T or F.

I am wondering what command would be best to do this as I am stumped.
I then have to output the students score of a 1 if the answer matched the answer key, and a 0 if the answer did not match. There are a total of 10 characters of T or F in each string.

Would strncmp work?

Any advice would be much appreciated
If you want a single character in a string use the [] operator.

string mystring = "flame"; //mystring[0] = f;

A string can be thought of as an array of characters, so you can access each character individually.



strncmp only works with cstyle strings.

string thestandardstring; /*||*/ char* cstylestring;
What method you use would largely depend on what data type you use to store the string.

If you are just checking to see if the user has entered either the character 'T' or 'F', the simplest method (in my opinion) would be to store the character in a char variable, then do a regular comparison:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
char c;

//code to get the character from the input stream

if( c == 'T' || c == 't' )
{
    //do something
}
else if( c == 'F' || c == 'f' )
{
    //do something else
}
else
{
    //a character other than T or F has been pressed
}


If you stored the user input in character arrays: char sString[1024], you could use strcmp() or strncmp(). Be aware that strncmp() works similarly to strcmp() but also takes into consideration the number of characters you want to compare.

Information on them can be found here:
-strcmp(): http://www.cplusplus.com/reference/clibrary/cstring/strcmp/
-strncmp(): http://www.cplusplus.com/reference/clibrary/cstring/strncmp/

Another method could be to use the string class: #include <string> , and use the string::compare(...) method.

Information on the string class can be found here: http://www.cplusplus.com/reference/string/string/

and information on the method string::compare() can be found here: http://www.cplusplus.com/reference/string/string/compare/

Hope this helps!
Topic archived. No new replies allowed.