Can a variable be initialized with an istream on the same line it is declared? [duplicate]

☆樱花仙子☆ 提交于 2019-12-04 01:56:41

The smart-ass answer:

int old; std::cin >> old;

The horrible answer:

int old, dummy = (std::cin >> old, 0);

The proper answer: old has to be defined with a declaration before it can be passed to operator>> as an argument. The only way to get a function call within the declaration of a variable is to place it in the initialization expression as above. The accepted way to declare a variable and read input into it is as you have written:

int old;
std::cin >> old;

You can... with

int old = (std::cin >> old, old);

but you really should not do this

Using a function:

int inputdata()
{
    int data;
    std::cin >> data;
    return data;
}

Then:

int a=inputdata();

For data itself:

int inputdata()
{
    static bool isDataDeclared=false;
    if (isDataDeclared==true)
    {
    goto read_data;
    }
    else
    {
        isDataDeclared=true;
    }
    static int data=inputdata();
    return data;
    read_data:
    std::cin >> data;
    return data;
}

Maybe not for int, but for your own types:

class MyType {
    int value;
public:
    MyType(istream& is) {
        is >> *this;
    }

    friend istream& operator>>(istream& is, MyType& object);
};  

istream& operator>>(istream& is, MyType& object) {
    return is >> object.value;
}

Then you can create the type with the istream passed to the constructor:

int main() {
    istringstream iss("42");
    MyType object(iss);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!