Reputation: 19
I'm trying to use a for each loop to iterate through a vector of strings, but I keep getting an error that says:
expected initializer before ':' token
.
This is my code:
#include <string>
#include <vector>
#include <iostream>
std::vector<std::string> tokens {"Dog","Ship","Coffee","Laptop","Shoe","McDonald's Cup","Airplane","Cellphone"};
int token_num=1;
for (std:string& token : tokens) {
std::cout<<token_num<<": "<<token<<"\n";
token_num++;
}
I've also tried:
std::vector<std::string> tokens {"Dog","Ship","Coffee","Laptop","Shoe","McDonald's Cup","Airplane","Cellphone"};
int token_num=1;
for (const auto& token : tokens) {
std::cout<<token_num<<": "<<token<<"\n";
token_num++;
}
but I'm getting the same error. What am I doing wrong?
Upvotes: 1
Views: 602
Reputation: 97
Seems like you are missing int main()
Check this out, this works fine.
#include<bits/stdc++.h>
using namespace std;
int main(){
vector<string> tokens {"Dog","Ship","Coffee","Laptop","Shoe","McDonald's Cup","Airplane","Cellphone"};
int token_num=1;
for (string& token : tokens) {
cout<<token_num<<": "<<token<<"\n";
token_num++;
}
token_num=1;
for (const auto& token : tokens) {
cout<<token_num<<": "<<token<<"\n";
token_num++;
}
return 0;
}
Upvotes: 1