user1988385
user1988385

Reputation: 2869

Iterate through string char by char

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

Upvotes: 16

Views: 81346

Answers (4)

Mark Tolonen
Mark Tolonen

Reputation: 177600

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;
}

Upvotes: 28

David G
David G

Reputation: 96810

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.

Upvotes: 6

billz
billz

Reputation: 45410

std::string::c_str() returns const char*, you can't use char& to hold it. Also exp is pointer already, you don't need reference:

Better use iterator though:

void print(const string& infix)
{
  for (auto c = infix.begin(); c!=infix.end(); ++c)
  {
    std::cout << *c << "\n";
  }
  std::cout << std::endl;
}

To fix your original code, try:

void print(const string& infix)
{
  const char *exp = infix.c_str();
  while(*exp!='\0')
  {
    cout << *exp << endl;
    exp++;
   }
 }

Upvotes: 0

Dhaivat Pandya
Dhaivat Pandya

Reputation: 6536

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".

Upvotes: 15

Related Questions