+ 2

im still a newbie and I see 2 approaches used to write code in C++, can you guys help me understand with CLEAR EXPLANATION?

// Example program 1 (random approach?) #include <iostream> #include <string> // write or dont, result is same int main() { std::string name; std::cout << "What is your name? "; getline (std::cin, name); std::cout << "Hello, " << name << "!\n"; } // Example program 2 (sololearn approach) #inlcude <iostream> using namespace std; int main() { cout << "whats your name?"; string name; cin >> name << endl; cout "Hello, " << name << "!\n"; return 0; } also, does solo learn C++ course tell us this in the future?

15th Oct 2019, 6:01 PM
mohsin khan
mohsin khan - avatar
5 Answers
+ 5
As long as another namespace that you are using does not have cout, cin etc. (which is unlikely) the second way is better.
16th Oct 2019, 12:26 AM
Sonic
Sonic - avatar
+ 3
use example 2, it's a good programming habit to use using namespace std and return 0 since main function returns an integer.
15th Oct 2019, 8:15 PM
Shen Bapiro
Shen Bapiro - avatar
+ 2
They're the same thing, it doesn't matter which one you use, but the second one is definetly better, as long as there are no conflicts
15th Oct 2019, 6:53 PM
Aymane Boukrouh
Aymane Boukrouh - avatar
0
example 2 includes the line "using namespace std" as to avoid having to add std:: prefix all over the code as in example1, thus making the code easier to read . if the code was using same named methods from different libraries, syntax from example1 is useful (but this is not the case here, and both examples are equivalent.)
16th Oct 2019, 6:24 AM
ifl
ifl - avatar