开发者

defining stringstream and string inside if

开发者 https://www.devze.com 2022-12-14 01:43 出处:网络
is there a way to define std::string and std::stringstream inside if or main function as a parameter

is there a way to define std::string and std::stringstream inside if or main function as a parameter

example

main(int d,int m)
{
if(std::cin>>d)
{}
if(std::stringstream ss,std::string s)
{}


}

it is giving the error

expected primary-expression before ‘ss’
开发者_高级运维error: expected `)' before ‘ss’


As this is C++ main must have a return type in it's declaration. The actual error that you are getting seems to indicate that you need to #include <sstream> at some point.

While you can declare a variable inside an if's condition expression it's not a feature that's used very often and the one object that's constructed must have an valid implicit conversion sequence to a bool. You can't use a , to attempt to declare two variables, it's not a valid expression for an if clause.

If construction of any object fails then an exception will have to have been thrown so this isn't a necessary or correct way to test for construction failure. You should probably just declare your variables in the function scope of main.


Anything returning any value like any function call can be done inside if but you can not declare variables in that, really silly.

This can be done as printf will return some value and if will check that return value for condition

 if(printf("Hello"))

but not this

if(std::string str)


The only valid pattern is:

Base* b = ...;
if (Derived* d = dynamic_cast<Derived*>(b)) {
  d->stuff();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消