In the new C++ standard, C++11, one can use range based for loop for processing every character of string.
#include<iostream>
#include<string>
int main()
{
std::string s1 = "this is an example";
for (char &c:s1)
//do any operation
std::cout<<c;
return 0;
}
Instead of reference char &c:s1 how can I use a pointer to do that in range based for loop? I want to do something like char *p pointing to s1.
The range-based for loop will not give you a pointer. However, you can make one:
for (char &c : s) {
char *p = &c;
}
Or you can do it yourself with a regular loop:
// Note: Requires C++17, where s.data() is relaxed to a char* type.
for (char *p = s.data(), *e = p + s.size(); p != e; p++) {
}
// Pre-C++17 version.
for (char *p = &s[0], *e = p + s.size(); p != e; p++) {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With