1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
|
// strbrk test
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
char * strbrk( char *s1, char *s2);
int main()
{
struct TestCase
{
char s1[64]; // using char buffers as strbrk() takes non-const char *s
char s2[64];
char expectedResult[64];
int expectedOffset;
};
static TestCase testCases[] = {
{"abc", "a", "abc" , 0},
{"abc", "b", "bc" , 1},
{"abc", "c", "c" , 2},
{"abc", "d", "NULL" , 0}
};
static const int count = sizeof(testCases)/sizeof(testCases[0]);
int passes = 0;
for(int i = 0; i < count; ++i)
{
TestCase& tc = testCases[i];
cout << "TestCase #" << (i + 1) << "\n"
<< "s1 = " << tc.s1 << "\n"
<< "s2 = " << tc.s2 << "\n";
char* p = strbrk(tc.s1, tc.s2);
bool passed = false;
if(p == NULL)
{
cout << "p = NULL\n";
passed = (0 == strcmp(tc.expectedResult, "NULL"));
}
else
{
cout << "p = " << p << "\n"
<< "offset = " << (p - tc.s1) << "\n";
passed = ( (0 == strcmp(p, tc.expectedResult))
&& ((p - tc.s1) == tc.expectedOffset) );
}
if(passed)
{
cout << "- pass!\n";
++passes;
}
else
{
cout << "- fail!\n";
}
cout << "\n";
}
cout << "Passed " << passes << " out of " << count << " test cases.\n";
return 0;
}
char * strbrk( char *s1, char *s2)
{
char c;
while ((*s1++ = c) != 0)
{
for( ; *s2 != 0 ; ++s2 )
if (*s2 == c) // added * -- was s2 == c (which didn't compile)
return s1; // lost (char *) cast as s1 already a char*
}
return (NULL);
}
|