Search code examples
c++classscopereturn-type

Passing a list as a return type in c++?


User.h

#pragma once
#include <iostream>
#include <string>
#include <fstream>
#include <list>

class User
{
private:

char line1[50];
char line2[50];
char line3[50];
char line4[50];

public:

void getUser(std::string);
};

User.cpp

#include "User.h"

void getUser(std::string username)
{
std::ifstream fin(username + ".txt");
fin.getline(line1, 50);
fin.getline(line2, 50);
fin.getline(line3, 50);
fin.getline(line4, 50);
fin.close();

std::list<std::string> UserInfo;

UserInfo.push_back(line1);
UserInfo.push_back(line2);
UserInfo.push_back(line3);
UserInfo.push_back(line4);

return UserInfo;
}

main.cpp

#include "User.h"

std::string username;

User display;

std::cout << std::endl << "Please enter your username: ";
std::getline (std::cin, username);
display.getUser(username);

I want to access the list UserInfo in main - I'm assuming it has to be returned, however, I don't know what the return type would be? (void is just temporary until I know the return type).

The other problem I have is when accessing the char variables in User.cpp, line1, line2 etc, I am given the error:

Identifier "line1" is undefined.


Solution

  • Same as your list :

    std::list<std::string> getUser(std::string username)
    {
    
      return UserInfo ;
    }
    

    Or pass it as a reference :

    void getUser(std::string username, std::list<std::string>& UserInfo)
    {
    
    
    }
    

    Char arrays line1, etc are private members can be accessed inside the member functions of class or through friend functions only.

    Defined your getUser outside class

    void User::getUser(std::string username)
    {
    
    }