return value from function
Oct 14, 2017 at 12:55pm UTC
Hi guys I've got a dilemma I want to get the return value of a function and set it equal to a pointer in main,I know this can be achieved using a global pointer but I want to avoid using globals in this small project,
is there any way I can get the return value of the function without the function actually being displayed to the console?
thanks
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
map<string,string>* readFromDiary(){
map<string, string> entries;
ifstream in;
string date;
string description;
string fileName = "diary.txt" ;
in.open(fileName);
if (!in.is_open()) {
cout << "file could not be opened" << endl;
return NULL;
}
while (in) {
getline(in, date, ':' );
getline(in, description);
if (!in) {
break ;
}
cout << date;
cout << description;
cout << endl;
entries[date] = description;
}
return &entries;
}
void openDiary(){
}
int main() {
bool quit = false ;
map<string,string>* entries;
while (!quit){
entries = readFromDiary();
}
}
Oct 14, 2017 at 1:22pm UTC
Do not return a pointer to a local object. You can simply return the object itself:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
map<string,string> readFromDiary(){ // Note: no *
map<string, string> entries;
...
return entries; // Note: no &
}
...
int main() {
bool quit = false ;
map<string,string> entries; // Note: no *
while (!quit){
entries = readFromDiary();
}
}
Due to the move semantic it is nearly as effecient as returning a pointer because the content is not copied but moved.
Oct 14, 2017 at 1:34pm UTC
Alternatively pass by reference. Again, no pointer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
#include <iostream>
#include <string>
#include <map>
#include <fstream>
using std::cout;
using std::endl;
using std::string;
using std::map;
using std::ifstream;
bool readFromDiary( map<string, string>& entries)
{
string fileName = "diary.txt" ;
ifstream in(fileName);
if (!in)
{
cout << "file " << fileName << " could not be opened" << endl;
return false ;
}
string date;
string description;
while ( getline(in, date, ':' ), getline(in, description) )
{
// cout << date;
// cout << description;
// cout << endl;
entries[date] = description;
}
return (entries.size() != 0);
}
int main()
{
map<string,string> entries;
bool ok = readFromDiary(entries);
if (ok)
for (const auto & entry : entries)
cout << entry.first << " ..... " << entry.second << '\n' ;
else
cout << "No entries\n" ;
}
Oct 14, 2017 at 2:14pm UTC
thanks guys =)
Topic archived. No new replies allowed.