-2

I have this code:

#include <iostream> #include <string> using namespace std; class Event{ public: Event(int x, int y, string z){ setEvent(x, y, z); }//Constructor void setEvent(int a, int b, string c){ if(a >= 0){ if(a < b){ if(b <= 24){ start_time = a; end_time = b; event_name = c; } else cout <<"The end time for the event needs to be <=24 hours"; } else cout <<"The start time for the event needs to be smaller than the end time"; } else cout <<"The start time for the event needs to be >=0 hours"; }//Code to set an event and check if the event is valid within the precondition void rename(string r){//Code to rename event event_name = r; } string duration(){ int time_length = end_time - start_time; if(time_length == 1) return "1 hour";//I am stuck over here!!! else return time_length "hour"; } private: int start_time; int end_time; string event_name; }; 

If you look void duration() in the public class, I am trying to make return return text in one part and a var and text in another part. But I am unable to make it work.

 main.cpp:30:16: error: could not convert 'time_length' from 'int' to 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' else return time_length "hour"; ^~~~~~~~~~~ 

main.cpp:30:28: error: expected ';' before string constant else return time_length "hour"; ^~~~~~

Is there a way to make return work or any alternative to fix this problem/code.

9
  • 1
    1st of all you can't return anything from a void function. 2nd return something like a std::pair<int, std::string> for example. Commented Dec 19, 2017 at 0:49
  • Instead of giving it a downvote, please give feedback as well Commented Dec 19, 2017 at 0:50
  • @user0042 can you explain the 2nd you meant, it is unclear to what you mean. Commented Dec 19, 2017 at 0:51
  • @user0042 i know that is wrong to ask stuff, but why doesn't return text? Commented Dec 19, 2017 at 0:53
  • 1
    You might be looking for return std::to_string(time_length) + " hour"; Commented Dec 19, 2017 at 0:54

1 Answer 1

1

Using void means the function will return nothing, so you cannot actually retreive any variables from this function.

A fix would be to give the function type std::string, EG

string duration(){ int time_length = end_time - start_time; if(time_length == 1) return "1 hour";//I am stuck over here!!! else //Formulate a string otherwise } 

Note you are going to have to look into building a string with C++, and put that logic into your else statement.

If you wish to return a pair, you are going to have to write another function with return type std::pair<int, std::string>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.