I tried making a little program that checks if a string is a substring of another. I think got the logic down correctly, but i encountered a problem concerning data types. I declared 2 strings and gave them a value instantly and they worked fine, but the other one, the checker variable, works in a weird way. It can not be printed out like a regular string using cout but it only prints the first letter. And functions like .length() do not work on it, the error says
|error: request for member 'length' in 'checker', which is of non-class type 'std::__cxx11::string
Code:
#include <iostream> #include <string.h> #include <string> using namespace std; int main() { string text = "abcde"; string subtext = "bcde"; //string specialChars = "\\*"; string checker[subtext.length()]; int counter = 0; for(int i = 0; i < 5; i++){ if (subtext[counter] == text[i]){ checker[counter] = text[i]; counter++; } } cout << text << " " << checker.length() << endl; for (int i = 0; i < 4; i++){ cout << checker[i]; } return 0; } Bonus question ^_^: Is the logic behind the program good enough, or is there a more efficient way of solving it.
thanks a lot.
using namespace std;is a bad habit to get into and if you can stop now you might avoid a whole lot of headaches in the future. Thestd::prefix is there for a reason: It avoids conflict with your own classes, structures and variables especially when you’re importing a lot of header files which may define a lot more things than they superficially appear to.std::vector(which will as noted in an answer also solve your problem).