0

My question is based upon a video I was watching explaining how to use variables in javaScript. Now my question is how can variables be used in c++ programming. I am new to all this and even through it's awesome to be learning all this, it can be a bit annoying when you don't know what you are doing.
My second problem is if anyone can explain what's wrong with this code:

include <iostream>
using namespace std;
int main ()
    myName = Ravi
    foodType = Apple
    numberEaten = 3
{
    cout << myName, "ate" numberEaten, foodType, << endl;
}

It says:[Error] expected initializer before 'myName.

airhuff
  • 413
  • 6
  • 18
  • Why do you watch javascript videos when you want to learn c++? – tkausl Feb 12 '17 at 06:51
  • You don't understand basic C++ syntax. All the code in a function has to go in between the `{ }`. When you declare variables, you have to specify the type. And the syntax for outputting multiple things is `cout << thing1 << thing2 << thing3`, you don't separate them with commas. – Barmar Feb 12 '17 at 06:51
  • Javascript and C++ might *look* a little similar, but they are definitely not the same language. You can't really use your knowledge of the syntax in one language to learn the other. Instead I suggest you [find a good beginners book to read](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Some programmer dude Feb 12 '17 at 06:51
  • please at least mark my answer correct. – zoecarver Feb 12 '17 at 17:23

1 Answers1

1

C++ variables:
OK here it goes. First, C++ and JS are VERY different. In JS variables are defined with var <variable name> = something here;. The nice thing about Js is that it figures out the data-type of variables automatically without you having to explicitly write it, while the reverse is the case in C++ where you have to write it yourself. For example, for an integer you would use int x = 10; and for a string you would use string hello = "world"; (However you will need to add the string library to be able to do this).

Now for the C++ code fix:
You are doing several things wrong. I would personally try to learn the basics of C++ and then restart, but that is just me. First thing that is wrong:

1)You need to have # before you include.
2) You need to put the curly braces just after you start your function (this is the same in JS).
3) you need to define your variables the way I described above.
4) Don't use commas in cout.
5) You need to have quotes around your text
7) You need to have semicolon after every line of code.

here is an example of how you could fix your code:

#include <iostream>
#include <string>

using namespace std;

int main ()
{
  string myName = "Ravi" ; 
  string foodType = "Apple" ;
  int numberEaten = 3 ;
cout <<  myName << "ate" << numberEaten << foodType ;
return 0;
}
mbappai
  • 557
  • 1
  • 5
  • 22
zoecarver
  • 5,523
  • 2
  • 26
  • 56