I was trying to solve this problem but I think I am not doing the string handling part right. The problem is given a string (let's say "abc") write out all upper and lower case combinations of this string.
My approach was to modify binary counter method.
So here's my implementation:
#include <iostream> #include <cmath> #define LOWER_CASE_DIFF 'a'-'A' using namespace std; void changeSeq(string &in, int amount) { int i = 0; while (i < amount && (int)in[i] < 'a') { in[i] += LOWER_CASE_DIFF; i++; } if (i < amount) { in[i] -= LOWER_CASE_DIFF; } cout << in << endl; } int main() { string input = "abc"; int diff = 'a' - 'A'; //a is always bigger than A in ASCII int comb = (int)pow(2,(float)input.length()); for (int i = 1; i <= comb; i++) { changeSeq(input, i); } return 0; } I am getting this runtime error:
/usr/local/lib/gcc/i686-pc-linux-gnu/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.h:707: typename _Alloc::rebind<_CharT>::other::reference std::basic_string<_CharT, _Traits, _Alloc>::operator[](typename _Alloc::rebind<_CharT>::other::size_type) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]: Assertion '__pos < size()' failed. Disallowed system call: SYS_kill So how can I change one character at a time? Is strings behaviour in C++ similar to const char* str = "abc" in C, where array of characters are stored in constants?
input[6]is not valid if the string is less than 6 characters long. Did you at least debug to see where it breaks?(int)pow(2,(float)input.length())is a very bad idea. Floating-point numbers are not exact, so it is possible thatpow(2, 3) == 7.99999and thus(int)pow(2, 3) == 7...n!of those, and not2 ^ n.changeSeqit seems as if he just wants ABC AbC not BCA BaC .. so 2^n seems right