+ 1
If / loop conditions
Say that I have a short integer variable that I want to cin. Is it possible to make an if statement in c++, whereas if the input does not equal the variable’s type, it can cancel? Ex: if (myInteger != <type int>) {..... }
10 odpowiedzi
+ 3
Just as an fyi, typeid isn't very portable, while gcc and clang return "i" for typeid(myVar).name(), vc++ instead returns "int" and that's just a minor difference, things get much crazier there.
The better way to check if a type is an int, short, double or whatever is to use std::is_same<T,U>::value
For example:
int i = 0;
if /*constexpr*/( std::is_same<int, decltype( i )>::value )
{
std::cout << "int\n";
}
else if /*constexpr*/ ( std::is_same<double, decltype( i )>::value )
{
std::cout << "double\n";
}
else
{
std::cout << "not int nor double\n";
}
The if constexpr is a C++17 feature :)
+ 3
Personally I never use "using namespace std". I've never really used it since I began programming and now code that doesn't have std:: in it just looks weird to me. :)
There are definitely reasons when you shouldn't use it but they usually only become troublesome in big projects when you happen to use the same names as from the std namespace, most of the time you are perfectly fine using it for small applications.
Just because of that 'most of the time' I still recommend you drop it as soon as possible just so it becomes a habit to not use it as soon as possible or risk running into possibly weird bugs for when that 'most of the time' doesn't hold, it also looks more professional.
This thread pretty much lists the reason why you shouldn't:
https://www.sololearn.com/Discuss/294730/poll-what-is-your-opinion-on-the-teaching-and-usage-of-namespaces-in-c-should-we-stop-the-practice
---
Not sure if the 2nd part of your response is a question or just a statement. :)
+ 2
Serena Yvonne Sorry about that, I’m using basic Dev C++ Bloodshed (started c++ recently). I forgot SoloLearn is kind of weird with inputs 😬
+ 2
Dennis Noted. As a sidebar, i noticed a lot of people code without “using namespace std;” and instead do “std:: (code)”. Is there a preference? Or just the way people learn?
And constexpr I literally saw a few hours ago. It appeared on someone mentioning newer, better apps for c++ over using Bloodshed Dev C (what I use currently. It was recommend for ease of starting c++)
+ 2
Dennis I see... I thought about learning both ways in order to be more flexible. Std namespace always seemed like training wheels, so thanks for that! Also the second part was a statement, so no worries
+ 1
Serena Yvonne Hate to trouble you once more, but I have a new dilemma.
When it recognizes the foreign character in my if statement, it runs an infinite loop...
In my code, i have a short int “level_requirement”.
I will post my code to show you