Home > Net >  I want the user to input the day number as the value of the parameter of the called function using c
I want the user to input the day number as the value of the parameter of the called function using c

Time:01-27

So, as you see in the question I want to make the user input the value of the arguement daynum down when I call the function getday, and not me who enters it. However I can't seem to get it right. I have tried cin << getday(); but it's wrong I looked in the internet to get an idea I guess and I tried getday(cin); but still it's wrong kinda clueless here about how to use cin with the function call.

#include <iostream>

using namespace std;

string getday(int daynum){
    string dayname;
switch(daynum){
case 0:
    dayname = "sunday";
    break;
case 1:
    dayname = "Monday";
    break;
case 2:
    dayname = "Tuesday";
    break;
default:
   dayname = "invalid day number";


}
return dayname;
}


int main()
{

cout << "Enter daynum" << endl;



    return 0;
}

CodePudding user response:

You have to create a temporary variable, fill it with user value using cin, and then pass it to your function:


string getday(int daynum)
{
    string dayname;
    switch (daynum)
    {
        case 0:
            dayname = "sunday";
            break;
        case 1:
            dayname = "Monday";
            break;
        case 2:
            dayname = "Tuesday";
            break;
        default:
            dayname = "invalid day number";
    }
    return dayname;
}

int main()
{
    cout << "Enter daynum" << endl;
    int daynum;
    cin >> daynum;
    cout << getday(daynum) << endl;

    return 0;
}

CodePudding user response:

Also you can avoid the switch statement using an array or other data structure. It will be more cleaner and easier to mantain.

Example:

#include <iostream>
#include <array>
#include <string>

int main()
{
    std::array<std::string, 7> names = {"Monday", "Tuesday" , "Wendesday" , "Thursday", "Friday", "Saturday", "Sunday"};
    unsigned int n = 0; 
    std::cin >> n;
    if(n < names.size()) {
        std::cout << names[n] << std::endl;
    }
    else 
    {
        std::cout << "Invalid day number" << std::endl;
    }    
}

CodePudding user response:

You need to add some value in daynumby using cin inside main() or getday.

   #include <iostream>

using namespace std;

string getday(int daynum){
    string dayname;
switch(daynum){
case 0:
    dayname = "sunday";
    break;
case 1:
    dayname = "Monday";
    break;
case 2:
    dayname = "Tuesday";
    break;
default:
   dayname = "invalid day number";


}
return dayname;
}


int main()
{

int num ; // Here i create variable num  --> to pass argument to getday function 

cout << "Enter daynum" << endl;
cin>>num;

cout<<getday(num);


    return 0;
}
  •  Tags:  
  • Related