How do I read a string char by char in C++?
The simplest way to iterate through a string character by character is a range-for:
bool Class::func(const string& cont){
for (char c : cont) {
if (c == '(') { ap++; }
if (c == ')') { ch++; }
}
//...
};
The range-for syntax was added in C++11. If, for some reason, you're using an old compiler that doesn't have C++11 support, you can iterate by index perfectly well without any casts or copies:
bool Class::func(const string& cont){
for (size_t i = 0; i < cont.size(); ++i) {
if (cont[i] == '(') { ap++; }
if (cont[i] == ')') { ch++; }
}
//...
};
If you just want to count the opening and closing parentheses take a look at this:
bool Class::func(const string& cont) {
for (const auto c : cont) {
switch (c) {
case '(': ++ap; break;
case ')': ++ch; break;
}
}
// ...
}
const string *p = &cont;
int k = 0;
while (p[k].compare('\0') != 0)
Treats p
as if it were an array, as p
only points to a single value your code has undefined behaviour when k
is non-zero. I assume what you actually wanted to write was:
bool Class::func(const string& cont){
while (cont[k] != '\0') {
if (cont[k] == '(') { ap++; };
if (cont[k] == ') { ch++; };
k++;
};
};
A simpler way would be to iterate over std::string
using begin()
and end()
or even more simply just use a range for loop:
bool Class::func(const string& cont){
for (char ch : cont) {
if (ch == '(') { ap++; };
if (ch == ')') { ch++; };
};
};
If you want to copy your string simply declare a new string:
std::string copy = cont;