Passing input as a function argument using cin

元气小坏坏 提交于 2019-12-19 03:11:09

问题


My program:

class test
{
    int k;
    public:
    void changeval(int i){k=i;}
};
int main()
{   
    test obj; 
    int i;
    cin>>i;
    obj.changeval(i);
    return 0;
}

Is there any way, by which i can directly pass input from the user as an argument to the function changeval(int), without even initializing value to i??

I mean, i don't want to declare a variable just to pass value to a function. Is there any way i can avoid it? If yes, can I use it for constructors also? Thanks.


回答1:


Nope. Now, you could put this into a function:

int readInt(std::istream& stream)
{
    int i;
    stream >> i; // Cross your fingers this doesn't fail
    return i;
}

// Then in your code:
obj.changeval(readInt(std::cin));

But of course, this still creates an int (it just moves it to the readInt function).

In reality, you have to create some object/memory space for the int to live in, so you can read it and pass it. Where you do this can be changed. But to simply answer your question: no.




回答2:


You may do it like this:

void changeval(istream& in) { in >> k; }
...
changeval(cin);

Is that what you need?



来源:https://stackoverflow.com/questions/20925828/passing-input-as-a-function-argument-using-cin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!