I'm using C++14 and trying to create a for each loop that prints out each string of the array. I get the error:
user.cpp:12:34: error: invalid initialization of reference of type ‘std::string& {aka std::basic_string&}’ from expression of type ‘char’
for(std::string &str : *(u->favs)){
When I change the std::string to auto in the foreach loop, it works but str becomes individual characters of the first string in the favs array. My code is as follows:
user.h
class User{
private:
public:
User(){
favs = new std::string[5]{std::string("Hello"), std::string("how"), std::string("are"), std::string("you"), std::string("?")};
}
~User(){
delete[] favs;
}
std::string lName;
std::string fName;
int age;
std::string *favs;
};
user.cpp
#include <iostream>
#include "user.h"
void create(User *u){
std::cout << "Please enter first name: ";
std::cin >> u->fName;
std::cout << "Please enter last name: ";
std::cin >> u->lName;
std::cout << "Please enter age: ";
std::cin >> u->age;
for(std::string &str : *(u->favs)){
std::cout << str << std::endl;
}
std::cout << "\n";
}
main.cpp
#include <iostream>
#include <string>
#include "user.h"
int main(){
std::string command;
User user;
std::cout << "bp1: " << user.favs->size() << std::endl;
while(true){
std::cout << "Please enter a command (Create, Update, View, Favorites, or Quit): ";
std::cin >> command;
if(command == "Create"){
create(&user);
} else if(command == "Update"){
update(&user);
} else if(command == "View"){
view(&user);
} else if(command == "Favorites"){
//favorites(&user);
} else if(command == "Quit"){
break;
} else std::cout << "Please input a valid command.\n";
}
}