Monday, May 24, 2010

C++ Vectors?

The instructions for this problem are:


" Write a complete program that reads in 100 double values from standard input (keyboard) into a vector. Then output all 100 values to standard output (terminal) in the same order they were read in with one space between each value."





I do not need to worry about prompting the user with instructions.





The code I have so far is:





#include %26lt;iostream%26gt;


#include %26lt;vector%26gt;





int main()


{


vector%26lt;double%26gt; values(99);





while( int i = 0 ; i %26lt;= 99 ; i++ )


{


cin %26lt;%26lt; vector[i];


}





for ( int i = 1 ; i %26lt; values.size()-1 ; i++ )


{


cout %26lt;%26lt; vector[i] %26lt;%26lt; " " ;


}





return 0;


}





Could someone please tell me what I am doing wrong? Thanks in advance.

C++ Vectors?
Here is correct code based on your code:





#include %26lt;iostream%26gt;


#include %26lt;vector%26gt;





using namespace std;


const static int vec_sz = 100;


vector%26lt;double%26gt; values(vec_sz);





int main( int ac, char * av[] )


{





for( int i = 0 ; i %26lt; vec_sz ; i++ )


{


cin %26gt;%26gt; values[i];


}





for ( int i = 0 ; i %26lt; vec_sz ; i++ )


{


cout %26lt;%26lt; values[i] %26lt;%26lt; " " ;


}


return 0;


}
Reply:cin %26gt;%26gt; values[i]; (not %26lt;%26lt;)





and cout %26lt;%26lt; values[i], not vector[i]





if the cin doesn't work (vector::operator[] returns a reference so it should in theory) use a temporary double variable first then assign that into the vector.

chelsea flower show

No comments:

Post a Comment