There are 2 mistakes in your given example.
Mistake 1
You have written the statement:
char char_array[n + 1]; //since n is not a compile time constant so this is not standard C++
In C++, the size of an array must be a compile time constant. So you cannot write code like:
int n = 10;
int arr[n]; //incorrect
Correct way to write this would be:
const int n = 10;
int arr[n]; //correct
Mistake 2
You are trying to convert char to const char* as the error says in the compare() method.
If you just want to find out whether a given character occurs in a std::string then there are 2 options/solutions(maybe more).
Solution 1
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "qwertyuiopasdfghjklzxcvbnm";
char match = 'w'; //use char instead of std::string
for (int i = 0; i < s.length(); i++)
if (s[i] == match) {
cout << "element: "<< match <<" found at index: "<<i<<std::endl;
}
return 0;
}
As shown in the above solution 1 you don't need to create a separate array.
Solution 2
You can use std::string::find to find a given substring inside another string. This would look like:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "qertyuiowpasdfghjklzxcvbnm";
std::string match = "w"; //using std::string instead of char
std::size_t index = s.find(match);
if(index != std::string::npos)
{
std::cout<<"string: "<<match<<" found at index: "<<index<<std::endl;
}
else
{
std::cout<<"string: "<<match<<" not found"<<std::endl;
}
return 0;
}
The output of solution 2 can be seen here.
Solution 3
#include <iostream>
#include <string>
int main()
{
std::string s = "qertyuiopasdfwghjklzxcvbnm";
std::size_t index1 = s.find_first_of('w');
if(index1 != std::string::npos)
{
std::cout<<"found at index: "<<index1<<std::endl;
}
else
{
std::cout<<"not found"<<std::endl;
}
return 0;
}
w[0]instead. But I’m also very puzzled by why you would copy the string to a char array to begin with.for (auto c : s)would loop over the characters just fine (not to mention that this looks like something where thefindfunction might be more appropriate).