I try to iterate through a string char by char. I tried something like this:
void print(const string& infix)
{
char &exp = infix.c_str();
while(&exp!='\0')
{
cout<< &exp++ << endl;
}
}
So this function call print("hello"); should return:
h
e
l
l
o
I try using my code, but it doesn't work at all. btw the parameter is a reference not a pointer. Thank you
Your code needs a pointer, not a reference, but if using a C++11 compiler, all you need is:
void print(const std::string& infix)
{
for(auto c : infix)
std::cout << c << std::endl;
}
for(unsigned int i = 0; i<infix.length(); i++) {
char c = infix[i]; //this is your character
}
That's how I've done it. Not sure if that's too "idiomatic".
If you're using std::string
, there really isn't a reason to do this. You can use iterators:
for (auto i = inflix.begin(); i != inflix.end(); ++i) std::cout << *i << '\n';
As for your original code you should have been using char*
instead of char
and you didn't need the reference.
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