In C++ I have an array of strings, say:
string lines[3]
lines[0] = 'abcdefg'
lines[1] = 'hijklmn'
lines[2] = 'opqrstu'
is there a way to loop through the chars within each index as well as loop through the indexes? something like lines[i[j]]?
Try this code:
std::string lines[3];
lines[0] = "abcdefg";
lines[1] = "hijklmn";
lines[2] = "opqrstu";
for (int i=0; i < lines.length(); ++i) {
    for (int j=0; j < lines[i].length(); ++j) {
        std::cout << lines[i][j];
    }
}
If you have C++11, you can use range for loop and auto:
// Example program
#include <iostream>
#include <string>
int main()
{
   std::string lines[3];
   lines[0]="abcdefg";
   lines[1]="hijklm";
// for( auto line: lines)//using range for loop and auto here
   for(int i=0; i<3; ++i)
   {
       std::string::iterator it= lines[i].begin();
       //for ( auto &c : line[i]) //using range for loop and auto here
       for(; it!= lines[i].end(); ++it)
       {
           std::cout<<*it;
       }
       std::cout<<"\n";
  }
}
O/P
abcdefg
hijklm
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