Jul 26, 2016 at 12:36am UTC
I have been using a textbook to learn a bit of C++. The below code is an exact copy of what the textbook says to code, but the program will not build. Arrays only seem to work if i declare 'then' initialise as opposed to declare 'and' initialise which is a problem when the array is an axis of coordinates as it would take forever to type each possibility out individually. Other programs i have copied from the book build and work normally.
Have i set Xcode up wrong or something?
#include <iostream>
using namespace std ;
int main ()
{
float nums[3] ;
nums [0] = 1.5 ; nums[1] = 2.75 ; nums[2] = 3.25 ;
char name[5] = [ 'M','i','k','e', '\0' ]
int coords[2][3]; coords[2][3] = {{1,2,3},{4,5,6}} ;
}
cout<<"nums[0]:"<<nums[0]<<endl ;
cout<<"nums[1]:"<<nums[1]<<endl ;
cout<<"nums[2]:"<<nums[2]<<endl ;
cout<<"nums[0]:"<<nums[0]<<endl ;
cout<<"Text string: "<<name<<endl;
cout<<"coords[0][2]:"<<coords[0][2]<<endl;
cout<<"coords[1][2]:"<<coords[1][2]<<endl:
Jul 26, 2016 at 1:04am UTC
ORIGINAL CODE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#include <iostream>
using namespace std ;
int main ()
{
float nums[3] ;
nums [0] = 1.5 ; nums[1] = 2.75 ; nums[2] = 3.25 ;
char name[5] = [ 'M' ,'i' ,'k' ,'e' , '\0' ]
int coords[2][3]; coords[2][3] = {{1,2,3},{4,5,6}} ;
}
cout<<"nums[0]:" <<nums[0]<<endl ;
cout<<"nums[1]:" <<nums[1]<<endl ;
cout<<"nums[2]:" <<nums[2]<<endl ;
cout<<"nums[0]:" <<nums[0]<<endl ;
cout<<"Text string: " <<name<<endl;
cout<<"coords[0][2]:" <<coords[0][2]<<endl;
cout<<"coords[1][2]:" <<coords[1][2]<<endl:
The final brace in line 17 is wrong. It should be after line 25.
Line 12 is wrong too. It should be
char name[5] = { 'M' ,'i' ,'k' ,'e' , '\0' };
.
Now about line 14... You can only initialize arrays like that on definition, so it should be only
int coords[2][3] = {{1,2,3},{4,5,6}} ;
In the end of line 25, it's expected a
;
instead of
:
.
EXPECTED CODE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
#include <iostream>
using namespace std ;
int main ()
{
float nums[3] ;
nums [0] = 1.5 ; nums[1] = 2.75 ; nums[2] = 3.25 ;
char name[5] = { 'M' ,'i' ,'k' ,'e' , '\0' };
int coords[2][3] = {{1,2,3},{4,5,6}} ;
cout<<"nums[0]:" <<nums[0]<<endl ;
cout<<"nums[1]:" <<nums[1]<<endl ;
cout<<"nums[2]:" <<nums[2]<<endl ;
cout<<"nums[0]:" <<nums[0]<<endl ;
cout<<"Text string: " <<name<<endl;
cout<<"coords[0][2]:" <<coords[0][2]<<endl;
cout<<"coords[1][2]:" <<coords[1][2]<<endl;
}
Last edited on Jul 26, 2016 at 1:50pm UTC
Jul 26, 2016 at 1:06pm UTC
Thank you so much for your help! All works perfectly now.