I have the code below:
#include <iostream>
#include <list>
using namespace std;
class YTchannel{
public:
string name;
string owner;
int subs;
list<string> video_title;
};
int main(){
YTchannel ytc;
ytc.video_title={"A", "B", "C"};
for(string videotitle: ytc.video_title){
for(int i=1;i<=videotitle.size();i++){
cout<<i<<videotitle<<endl;
break;
}
}
I want to display the list of video titles with their respective number:
1A
2B
3C
But if I run the code, i’ll obtain:
1A
1B
1C
>Solution :
You have a ‘break’ in your loop so you never increment the counter.
Additionally, in C++20 you can narrow the scope, by using the init statement in range-based loop.
#include <iostream>
#include <list>
using namespace std;
class YTchannel{
public:
string name;
string owner;
int subs;
list<string> video_title;
};
int main(){
YTchannel ytc;
ytc.video_title={"A", "B", "C"};
int counter = 0;
for(string videotitle : ytc.video_title){
cout<<++counter<<videotitle<<endl;
}
// C++20
//YTchannel ytc;
//ytc.video_title={"A", "B", "C"};
//for(int counter = 0; string videotitle : ytc.video_title){
// cout<<++counter<<videotitle<<endl;
//}
}