c++ubuntu-15.04

C++ on ubuntu hello world


I'm trying to write my first code on ubuntu terminal using c++ .I created a new cpp file named aaa by

"nano aaa.cpp"

then inside I wrote

#include<iostream>
using std::cout;
using std::endl;

int main(int argc, car** argv)
{
   cout << "hello" << endl;
   return 0; 
}

i saved and got out but when i tried typing

g++ aaa.cpp

I got the error

error: ‘endl’ was not declared in this scope cout << "hello" << endl;

where did I go wrong I tried

$ sudo apt-get remove g++ libstdc++-6.4.7-dev
$ sudo apt-get install build-essential g++-multilib

but it was no good

any help?


Solution

  • Stylistically, I prefer to be explicit: std::cout and std::endl.

    #include <iostream>
    
    int main(int argc, char** argv) {
      std::cout << "hello" << std::endl;
      return 0; 
    }
    

    This also fixes a tyo of yours: char, not car and repairs the #include.

    This works as expected:

    $ g++ -Wall -pedantic -o foo2 foo2.cpp
    $ ./foo2
    hello
    $ 
    

    If you wanted to, you could also use

    using namespace std;
    

    but as stated, I prefer to more explicit form.

    Edit: Nothing as much fun as debating the beancounters. OP question is likely having _another error he is not sharing. His code, repaired for char actually builds:

    $ cat foo3.cpp 
    #include <iostream>
    using std::cout;
    using std::endl;
    
    int main(int argc, char** argv) {
      cout << "hello" << endl;
      return 0; 
    }
    $ g++ -Wall -pedantic -o foo3 foo3.cpp
    $ ./foo3
    hello
    $ 
    

    Ubuntu 16.04, g++ 5.4.0