简体   繁体   中英

c++ if statement with compound value

i'm trying to find a solution that allows me to take this snip:

cout << antalVaerelser << ("-v\x91r, ") 
<< (altan == true ? ("med altan, ") : ("uden altan, "));

if (etage == 0) {
cout << ("stuen ");
}
else {
cout << etage << (" etage ");
}

cout << areal << (" m2") << endl;

and transform it at bit to have a line that is more like this:

cout << antalVaerelser << ("-v\x91r, ")
<< (altan == true ? ("med altan, ") : ("uden altan, "))
<< (etage==0?("stuen ") : etage + (" etage "))
<< areal << (" m2")
<< endl;

however this does not work as some of the output seems to be "eaten" - it would be displayed as "4-vær, med altan, age, 101m2" where "age" should have been the value of etage (value=1-4) followed by the string " etage, "

This would also work, but it seems really excessive:

(etage == 0 ? ("stuen ") : etage == 1 ? ("1 etage ") : etage == 2 ? ("2 etage ") : etage == 3 ? ("3 etage ") : ("4 etage "))

so the question is thus: how (if at all possible) would i something like this work?:

(etage==0?("stuen ") : etage + (" etage ")) 

thank you in advance :)

There are two problems

  • ternary operator must return values of same type
  • adding integer and string literal doesn't work as you are expecting

to do it in C++11

cout << antalVaerelser << ("-v\x91r, ")
    << (altan == true ? "med altan, " : "uden altan, ")
    << (etage==0 ? std::string("stuen ") : std::to_string(etage) + " etage ")
    << areal << (" m2")
    << endl;

in C++14 a bit nicer:

cout << antalVaerelser << ("-v\x91r, ")
    << (altan == true ? "med altan, " : "uden altan, ")
    << (etage==0 ? "stuen "s : std::to_string(etage) + " etage "s)
    << areal << (" m2"s)
    << endl;

You can't concatenate the int and the string like that.

Try wrapping an int in std::to_string(myInt) then adding a string to that, that forces it to be string + string concatenation like you want.

Reference: http://en.cppreference.com/w/cpp/string/basic_string/to_string

You need to convert the number to string like this:

cout << (etage == 0 ? "stuen " : std::to_string(etage) + " etage");

std::to_string() helps you to convert your int' to string`.

You can also do it like this if it is just a concatenation matter:

etage == 0 ? cout << "stuen " : cout << etage <<" etage";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM